From 0a88c63a1cb0564958f8b2f9d9d11d504284a229 Mon Sep 17 00:00:00 2001 From: Alexander Fenster Date: Thu, 21 Nov 2019 23:27:08 -0800 Subject: [PATCH] feat: convert v3beta1 to TypeScript (#389) * feat: convert v3beta1 to TypeScript * fix: gts fix * fix: no npx --- package.json | 9 +- protos/google/cloud/common_resources.proto | 68 + protos/protos.d.ts | 30 + protos/protos.js | 104 +- protos/protos.json | 14 + src/index.ts | 67 +- src/v3/translation_service_client.ts | 73 + .../v3beta1/doc_translation_service.js | 931 ----------- .../doc/google/longrunning/doc_operations.js | 63 - src/v3beta1/doc/google/protobuf/doc_any.js | 137 -- .../doc/google/protobuf/doc_timestamp.js | 117 -- src/v3beta1/doc/google/rpc/doc_status.js | 95 -- src/v3beta1/{index.js => index.ts} | 10 +- ...lient.js => translation_service_client.ts} | 1470 +++++++++-------- .../translation_service_client_config.json | 24 +- synth.metadata | 15 +- synth.py | 27 +- system-test/.eslintrc.yml | 3 +- system-test/fixtures/sample/src/index.js | 1 - system-test/fixtures/sample/src/index.ts | 1 - test/gapic-translation_service-v3beta1.ts | 565 +++++++ test/gapic-v3beta1.js | 709 -------- 22 files changed, 1672 insertions(+), 2861 deletions(-) create mode 100644 protos/google/cloud/common_resources.proto delete mode 100644 src/v3beta1/doc/google/cloud/translation/v3beta1/doc_translation_service.js delete mode 100644 src/v3beta1/doc/google/longrunning/doc_operations.js delete mode 100644 src/v3beta1/doc/google/protobuf/doc_any.js delete mode 100644 src/v3beta1/doc/google/protobuf/doc_timestamp.js delete mode 100644 src/v3beta1/doc/google/rpc/doc_status.js rename src/v3beta1/{index.js => index.ts} (68%) rename src/v3beta1/{translation_service_client.js => translation_service_client.ts} (50%) create mode 100644 test/gapic-translation_service-v3beta1.ts delete mode 100644 test/gapic-v3beta1.js diff --git a/package.json b/package.json index 98e5facc..ce6c5a6f 100644 --- a/package.json +++ b/package.json @@ -30,14 +30,11 @@ "scripts": { "docs": "jsdoc -c .jsdoc.js", "predocs": "npm run compile", - "lint": "npm run check && eslint '**/*.js'", + "lint": "gts check && eslint '**/*.js'", "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", "system-test": "mocha build/system-test --timeout 600000", "test": "c8 mocha build/test", - "check": "gts check", - "clean": "gts clean", - "compile": "tsc -p . && npm run copy-js", - "copy-js": "cp -r src/v3beta1 build/src/ && cp -r protos build/ && cp test/*.js build/test", + "compile": "tsc -p . && cp -r protos build/", "fix": "gts fix && eslint --fix '**/*.js'", "prepare": "npm run compile", "pretest": "npm run compile", @@ -50,7 +47,7 @@ "@google-cloud/promisify": "^1.0.0", "arrify": "^2.0.0", "extend": "^3.0.2", - "google-gax": "^1.7.5", + "google-gax": "^1.11.1", "is": "^3.2.1", "is-html": "^2.0.0", "protobufjs": "^6.8.8" diff --git a/protos/google/cloud/common_resources.proto b/protos/google/cloud/common_resources.proto new file mode 100644 index 00000000..5d795bff --- /dev/null +++ b/protos/google/cloud/common_resources.proto @@ -0,0 +1,68 @@ +// Copyright 2019 Google LLC. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// This file contains stub messages for common resources in GCP. +// It is not intended to be directly generated, and is instead used by +// other tooling to be able to match common resource patterns. +syntax = "proto3"; + +package google.cloud; + +import "google/api/resource.proto"; + + +message Project { + option (google.api.resource) = { + type: "cloudresourcemanager.googleapis.com/Project" + pattern: "projects/{project}" + }; + + string name = 1; +} + +message Organization { + option (google.api.resource) = { + type: "cloudresourcemanager.googleapis.com/Organization" + pattern: "organizations/{organization}" + }; + + string name = 1; +} + +message Folder { + option (google.api.resource) = { + type: "cloudresourcemanager.googleapis.com/Folder" + pattern: "folders/{folder}" + }; + + string name = 1; +} + +message BillingAccount { + option (google.api.resource) = { + type: "cloudbilling.googleapis.com/BillingAccount" + pattern: "billingAccounts/{billing_account}" + }; + + string name = 1; +} + +message Location { + option (google.api.resource) = { + type: "locations.googleapis.com/Location" + pattern: "projects/{project}/locations/{location}" + }; + + string name = 1; +} diff --git a/protos/protos.d.ts b/protos/protos.d.ts index c9915730..1ae026a4 100644 --- a/protos/protos.d.ts +++ b/protos/protos.d.ts @@ -1,3 +1,18 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import * as Long from "long"; import * as $protobuf from "protobufjs"; /** Namespace google. */ export namespace google { @@ -6774,6 +6789,12 @@ export namespace google { /** ResourceDescriptor history */ history?: (google.api.ResourceDescriptor.History|null); + + /** ResourceDescriptor plural */ + plural?: (string|null); + + /** ResourceDescriptor singular */ + singular?: (string|null); } /** Represents a ResourceDescriptor. */ @@ -6797,6 +6818,12 @@ export namespace google { /** ResourceDescriptor history. */ public history: google.api.ResourceDescriptor.History; + /** ResourceDescriptor plural. */ + public plural: string; + + /** ResourceDescriptor singular. */ + public singular: string; + /** * Creates a new ResourceDescriptor instance using the specified properties. * @param [properties] Properties to set @@ -8533,6 +8560,9 @@ export namespace google { /** FileOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); + + /** FileOptions .google.api.resourceDefinition */ + ".google.api.resourceDefinition"?: (google.api.IResourceDescriptor[]|null); } /** Represents a FileOptions. */ diff --git a/protos/protos.js b/protos/protos.js index 724b91d7..3bf1543a 100644 --- a/protos/protos.js +++ b/protos/protos.js @@ -1,3 +1,17 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + /*eslint-disable block-scoped-var, id-length, no-control-regex, no-magic-numbers, no-prototype-builtins, no-redeclare, no-shadow, no-var, sort-vars*/ (function(global, factory) { /* global define, require, module */ @@ -16442,6 +16456,8 @@ * @property {Array.|null} [pattern] ResourceDescriptor pattern * @property {string|null} [nameField] ResourceDescriptor nameField * @property {google.api.ResourceDescriptor.History|null} [history] ResourceDescriptor history + * @property {string|null} [plural] ResourceDescriptor plural + * @property {string|null} [singular] ResourceDescriptor singular */ /** @@ -16492,6 +16508,22 @@ */ ResourceDescriptor.prototype.history = 0; + /** + * ResourceDescriptor plural. + * @member {string} plural + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.plural = ""; + + /** + * ResourceDescriptor singular. + * @member {string} singular + * @memberof google.api.ResourceDescriptor + * @instance + */ + ResourceDescriptor.prototype.singular = ""; + /** * Creates a new ResourceDescriptor instance using the specified properties. * @function create @@ -16525,6 +16557,10 @@ writer.uint32(/* id 3, wireType 2 =*/26).string(message.nameField); if (message.history != null && message.hasOwnProperty("history")) writer.uint32(/* id 4, wireType 0 =*/32).int32(message.history); + if (message.plural != null && message.hasOwnProperty("plural")) + writer.uint32(/* id 5, wireType 2 =*/42).string(message.plural); + if (message.singular != null && message.hasOwnProperty("singular")) + writer.uint32(/* id 6, wireType 2 =*/50).string(message.singular); return writer; }; @@ -16573,6 +16609,12 @@ case 4: message.history = reader.int32(); break; + case 5: + message.plural = reader.string(); + break; + case 6: + message.singular = reader.string(); + break; default: reader.skipType(tag & 7); break; @@ -16630,6 +16672,12 @@ case 2: break; } + if (message.plural != null && message.hasOwnProperty("plural")) + if (!$util.isString(message.plural)) + return "plural: string expected"; + if (message.singular != null && message.hasOwnProperty("singular")) + if (!$util.isString(message.singular)) + return "singular: string expected"; return null; }; @@ -16670,6 +16718,10 @@ message.history = 2; break; } + if (object.plural != null) + message.plural = String(object.plural); + if (object.singular != null) + message.singular = String(object.singular); return message; }; @@ -16692,6 +16744,8 @@ object.type = ""; object.nameField = ""; object.history = options.enums === String ? "HISTORY_UNSPECIFIED" : 0; + object.plural = ""; + object.singular = ""; } if (message.type != null && message.hasOwnProperty("type")) object.type = message.type; @@ -16704,6 +16758,10 @@ object.nameField = message.nameField; if (message.history != null && message.hasOwnProperty("history")) object.history = options.enums === String ? $root.google.api.ResourceDescriptor.History[message.history] : message.history; + if (message.plural != null && message.hasOwnProperty("plural")) + object.plural = message.plural; + if (message.singular != null && message.hasOwnProperty("singular")) + object.singular = message.singular; return object; }; @@ -21118,6 +21176,7 @@ * @property {string|null} [phpMetadataNamespace] FileOptions phpMetadataNamespace * @property {string|null} [rubyPackage] FileOptions rubyPackage * @property {Array.|null} [uninterpretedOption] FileOptions uninterpretedOption + * @property {Array.|null} [".google.api.resourceDefinition"] FileOptions .google.api.resourceDefinition */ /** @@ -21130,6 +21189,7 @@ */ function FileOptions(properties) { this.uninterpretedOption = []; + this[".google.api.resourceDefinition"] = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) @@ -21304,6 +21364,14 @@ */ FileOptions.prototype.uninterpretedOption = $util.emptyArray; + /** + * FileOptions .google.api.resourceDefinition. + * @member {Array.} .google.api.resourceDefinition + * @memberof google.protobuf.FileOptions + * @instance + */ + FileOptions.prototype[".google.api.resourceDefinition"] = $util.emptyArray; + /** * Creates a new FileOptions instance using the specified properties. * @function create @@ -21371,6 +21439,9 @@ if (message.uninterpretedOption != null && message.uninterpretedOption.length) for (var i = 0; i < message.uninterpretedOption.length; ++i) $root.google.protobuf.UninterpretedOption.encode(message.uninterpretedOption[i], writer.uint32(/* id 999, wireType 2 =*/7994).fork()).ldelim(); + if (message[".google.api.resourceDefinition"] != null && message[".google.api.resourceDefinition"].length) + for (var i = 0; i < message[".google.api.resourceDefinition"].length; ++i) + $root.google.api.ResourceDescriptor.encode(message[".google.api.resourceDefinition"][i], writer.uint32(/* id 1053, wireType 2 =*/8426).fork()).ldelim(); return writer; }; @@ -21470,6 +21541,11 @@ message.uninterpretedOption = []; message.uninterpretedOption.push($root.google.protobuf.UninterpretedOption.decode(reader, reader.uint32())); break; + case 1053: + if (!(message[".google.api.resourceDefinition"] && message[".google.api.resourceDefinition"].length)) + message[".google.api.resourceDefinition"] = []; + message[".google.api.resourceDefinition"].push($root.google.api.ResourceDescriptor.decode(reader, reader.uint32())); + break; default: reader.skipType(tag & 7); break; @@ -21580,6 +21656,15 @@ return "uninterpretedOption." + error; } } + if (message[".google.api.resourceDefinition"] != null && message.hasOwnProperty(".google.api.resourceDefinition")) { + if (!Array.isArray(message[".google.api.resourceDefinition"])) + return ".google.api.resourceDefinition: array expected"; + for (var i = 0; i < message[".google.api.resourceDefinition"].length; ++i) { + var error = $root.google.api.ResourceDescriptor.verify(message[".google.api.resourceDefinition"][i]); + if (error) + return ".google.api.resourceDefinition." + error; + } + } return null; }; @@ -21657,6 +21742,16 @@ message.uninterpretedOption[i] = $root.google.protobuf.UninterpretedOption.fromObject(object.uninterpretedOption[i]); } } + if (object[".google.api.resourceDefinition"]) { + if (!Array.isArray(object[".google.api.resourceDefinition"])) + throw TypeError(".google.protobuf.FileOptions..google.api.resourceDefinition: array expected"); + message[".google.api.resourceDefinition"] = []; + for (var i = 0; i < object[".google.api.resourceDefinition"].length; ++i) { + if (typeof object[".google.api.resourceDefinition"][i] !== "object") + throw TypeError(".google.protobuf.FileOptions..google.api.resourceDefinition: object expected"); + message[".google.api.resourceDefinition"][i] = $root.google.api.ResourceDescriptor.fromObject(object[".google.api.resourceDefinition"][i]); + } + } return message; }; @@ -21673,8 +21768,10 @@ if (!options) options = {}; var object = {}; - if (options.arrays || options.defaults) + if (options.arrays || options.defaults) { object.uninterpretedOption = []; + object[".google.api.resourceDefinition"] = []; + } if (options.defaults) { object.javaPackage = ""; object.javaOuterClassname = ""; @@ -21742,6 +21839,11 @@ for (var j = 0; j < message.uninterpretedOption.length; ++j) object.uninterpretedOption[j] = $root.google.protobuf.UninterpretedOption.toObject(message.uninterpretedOption[j], options); } + if (message[".google.api.resourceDefinition"] && message[".google.api.resourceDefinition"].length) { + object[".google.api.resourceDefinition"] = []; + for (var j = 0; j < message[".google.api.resourceDefinition"].length; ++j) + object[".google.api.resourceDefinition"][j] = $root.google.api.ResourceDescriptor.toObject(message[".google.api.resourceDefinition"][j], options); + } return object; }; diff --git a/protos/protos.json b/protos/protos.json index 38a285d9..f4f8d507 100644 --- a/protos/protos.json +++ b/protos/protos.json @@ -1683,6 +1683,12 @@ "id": 1055, "extend": "google.protobuf.FieldOptions" }, + "resourceDefinition": { + "rule": "repeated", + "type": "google.api.ResourceDescriptor", + "id": 1053, + "extend": "google.protobuf.FileOptions" + }, "resource": { "type": "google.api.ResourceDescriptor", "id": 1053, @@ -1706,6 +1712,14 @@ "history": { "type": "History", "id": 4 + }, + "plural": { + "type": "string", + "id": 5 + }, + "singular": { + "type": "string", + "id": 6 } }, "nested": { diff --git a/src/index.ts b/src/index.ts index 7a6c4b12..af42f24b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -14,54 +14,34 @@ * limitations under the License. */ -/** - * @namespace v2 - */ -/** - * @namespace google.cloud.translation.v3beta1 - */ -/** - * @namespace google.longrunning - */ -/** - * @namespace google.rpc - */ -/** - * @namespace google.protobuf - */ -const v3beta1 = require('./v3beta1'); import * as v2 from './v2'; /** * The `@google-cloud/translate` package has the following named exports: * - * - `{@link Translate}` class - constructor for v2 of the Translation API. - * See {@link Translate} and {@link ClientConfig} for client methods and - * configuration options. Provides TypeScript types out-of-the-box. + * - `{@link TranslationServiceClient}` class - constructor for v3 of the Translation API. + * See {@link v3.TranslationServiceClient} for client methods. + * - `v3` - client for the v3 backend service version. It exports: + * - `TranslationServiceClient` - Reference to {@link v3.TranslationServiceClient} * - `v3beta1` - client for the v3beta1 backend service version. It exports: - * - `TranslationServiceClient` - Reference to {@link - * v3beta1.TranslationServiceClient} - * + * - `TranslationServiceClient` - Reference to {@link v3beta1.TranslationServiceClient} + * - `v2` - client for the v2 backend service version. It exports: + * - `Translate` - Reference to {@link v2.Translate} * * @module {constructor} @google-cloud/translate * @alias nodejs-translate * - * @example Install the v2 client library with npm: npm install --save - * @google-cloud/translate + * @example Install the v3 client library with npm: + * npm install --save @google-cloud/translate * - * @example Import the v2 client library: - * const {Translate} = require('@google-cloud/translate'); + * @example Import the v3 client library: + * const {TranslationServiceClient} = require('@google-cloud/translate'); * - * @example Create a v2 client that uses Create a v3 client that uses Application Default Credentials - * (ADC): const client = new Translate(); - * - * @example Create a v2 client with explicit credentials: const client - * = new Translate({ projectId: 'your-project-id', keyFilename: - * '/path/to/keyfile.json', - * }); + * (ADC): + * const client = new TranslationServiceClient(); * * @example include:samples/quickstart.js * region_tag:translate_quickstart @@ -74,12 +54,17 @@ import * as v2 from './v2'; * const {TranslationServiceClient} = * require('@google-cloud/translate').v3beta1; */ +import * as v3beta1 from './v3beta1'; import * as v3 from './v3'; export * from './v3'; -/** - * @type {object} - * @property {constructor} TranslationServiceClient - * Reference to {@link v3beta1.TranslationServiceClient} - */ -export {v2, v3beta1, v3}; +const TranslationServiceClient = v3.TranslationServiceClient; +export {TranslationServiceClient, v2, v3beta1, v3}; +// For compatibility with JavaScript libraries we need to provide this default export: +// tslint:disable-next-line no-default-export +export default { + v2, + v3beta1, + v3, + TranslationServiceClient, +}; diff --git a/src/v3/translation_service_client.ts b/src/v3/translation_service_client.ts index 07b4cb78..cfc517bf 100644 --- a/src/v3/translation_service_client.ts +++ b/src/v3/translation_service_client.ts @@ -143,6 +143,9 @@ export class TranslationServiceClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this._pathTemplates = { + locationPathTemplate: new gaxModule.PathTemplate( + 'projects/{project}/locations/{location}' + ), glossaryPathTemplate: new gaxModule.PathTemplate( 'projects/{project}/locations/{location}/glossaries/{glossary}' ), @@ -1226,6 +1229,52 @@ export class TranslationServiceClient { // -------------------- // -- Path templates -- // -------------------- + + /** + * Return a fully-qualified location resource name string. + * + * @param {string} project + * @param {string} location + * @returns {string} Resource name string. + */ + locationPath(project: string, location: string) { + return this._pathTemplates.locationPathTemplate.render({ + project, + location, + }); + } + + /** + * Parse the project from Location resource. + * + * @param {string} locationName + * A fully-qualified path representing Location resource. + * @returns {string} A string representing the project. + */ + matchProjectFromLocationName(locationName: string) { + return this._pathTemplates.locationPathTemplate.match(locationName).project; + } + + /** + * Parse the location from Location resource. + * + * @param {string} locationName + * A fully-qualified path representing Location resource. + * @returns {string} A string representing the location. + */ + matchLocationFromLocationName(locationName: string) { + return this._pathTemplates.locationPathTemplate.match(locationName) + .location; + } + + /** + * Return a fully-qualified glossary resource name string. + * + * @param {string} project + * @param {string} location + * @param {string} glossary + * @returns {string} Resource name string. + */ glossaryPath(project: string, location: string, glossary: string) { return this._pathTemplates.glossaryPathTemplate.render({ project, @@ -1233,13 +1282,37 @@ export class TranslationServiceClient { glossary, }); } + + /** + * Parse the project from Glossary resource. + * + * @param {string} glossaryName + * A fully-qualified path representing Glossary resource. + * @returns {string} A string representing the project. + */ matchProjectFromGlossaryName(glossaryName: string) { return this._pathTemplates.glossaryPathTemplate.match(glossaryName).project; } + + /** + * Parse the location from Glossary resource. + * + * @param {string} glossaryName + * A fully-qualified path representing Glossary resource. + * @returns {string} A string representing the location. + */ matchLocationFromGlossaryName(glossaryName: string) { return this._pathTemplates.glossaryPathTemplate.match(glossaryName) .location; } + + /** + * Parse the glossary from Glossary resource. + * + * @param {string} glossaryName + * A fully-qualified path representing Glossary resource. + * @returns {string} A string representing the glossary. + */ matchGlossaryFromGlossaryName(glossaryName: string) { return this._pathTemplates.glossaryPathTemplate.match(glossaryName) .glossary; diff --git a/src/v3beta1/doc/google/cloud/translation/v3beta1/doc_translation_service.js b/src/v3beta1/doc/google/cloud/translation/v3beta1/doc_translation_service.js deleted file mode 100644 index b0fbadc0..00000000 --- a/src/v3beta1/doc/google/cloud/translation/v3beta1/doc_translation_service.js +++ /dev/null @@ -1,931 +0,0 @@ -// Copyright 2019 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Note: this file is purely for documentation. Any contents are not expected -// to be loaded as the JS file. - -/** - * Configures which glossary should be used for a specific target language, - * and defines options for applying that glossary. - * - * @property {string} glossary - * Required. Specifies the glossary used for this translation. Use - * this format: projects/* /locations/* /glossaries/* - * - * @property {boolean} ignoreCase - * Optional. Indicates match is case-insensitive. - * Default value is false if missing. - * - * @typedef TranslateTextGlossaryConfig - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.TranslateTextGlossaryConfig definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ -const TranslateTextGlossaryConfig = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * The request message for synchronous translation. - * - * @property {string[]} 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. - * - * @property {string} mimeType - * Optional. The format of the source text, for example, "text/html", - * "text/plain". If left blank, the MIME type defaults to "text/html". - * - * @property {string} 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. - * - * @property {string} 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. - * - * @property {string} 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. - * - * @property {string} 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. - * - * @property {Object} 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. - * - * This object should have the same structure as [TranslateTextGlossaryConfig]{@link google.cloud.translation.v3beta1.TranslateTextGlossaryConfig} - * - * @property {Object.} 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. - * - * @typedef TranslateTextRequest - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.TranslateTextRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ -const TranslateTextRequest = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * @property {Object[]} translations - * Text translation responses with no glossary applied. - * This field has the same length as - * `contents`. - * - * This object should have the same structure as [Translation]{@link google.cloud.translation.v3beta1.Translation} - * - * @property {Object[]} glossaryTranslations - * Text translation responses if a glossary is provided in the request. - * This can be the same as - * `translations` if no terms apply. - * This field has the same length as - * `contents`. - * - * This object should have the same structure as [Translation]{@link google.cloud.translation.v3beta1.Translation} - * - * @typedef TranslateTextResponse - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.TranslateTextResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ -const TranslateTextResponse = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * A single translation response. - * - * @property {string} translatedText - * Text translated into the target language. - * - * @property {string} model - * Only present when `model` is present in the request. - * This is same as `model` provided in the request. - * - * @property {string} detectedLanguageCode - * The BCP-47 language code of source text in the initial request, detected - * automatically, if no source language was passed within the initial - * request. If the source language was passed, auto-detection of the language - * does not occur and this field is empty. - * - * @property {Object} glossaryConfig - * The `glossary_config` used for this translation. - * - * This object should have the same structure as [TranslateTextGlossaryConfig]{@link google.cloud.translation.v3beta1.TranslateTextGlossaryConfig} - * - * @typedef Translation - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.Translation definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ -const Translation = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * The request message for language detection. - * - * @property {string} 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. - * - * @property {string} 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. - * - * @property {string} content - * The content of the input stored as a string. - * - * @property {string} mimeType - * Optional. The format of the source text, for example, "text/html", - * "text/plain". If left blank, the MIME type defaults to "text/html". - * - * @property {Object.} 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. - * - * @typedef DetectLanguageRequest - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.DetectLanguageRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ -const DetectLanguageRequest = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * The response message for language detection. - * - * @property {string} languageCode - * The BCP-47 language code of source content in the request, detected - * automatically. - * - * @property {number} confidence - * The confidence of the detection result for this language. - * - * @typedef DetectedLanguage - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.DetectedLanguage definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ -const DetectedLanguage = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * The response message for language detection. - * - * @property {Object[]} languages - * A list of detected languages sorted by detection confidence in descending - * order. The most probable language first. - * - * This object should have the same structure as [DetectedLanguage]{@link google.cloud.translation.v3beta1.DetectedLanguage} - * - * @typedef DetectLanguageResponse - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.DetectLanguageResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ -const DetectLanguageResponse = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * The request message for discovering supported languages. - * - * @property {string} 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. - * - * @property {string} 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. - * - * @property {string} 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. - * - * @typedef GetSupportedLanguagesRequest - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.GetSupportedLanguagesRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ -const GetSupportedLanguagesRequest = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * The response message for discovering supported languages. - * - * @property {Object[]} languages - * A list of supported language responses. This list contains an entry - * for each language the Translation API supports. - * - * This object should have the same structure as [SupportedLanguage]{@link google.cloud.translation.v3beta1.SupportedLanguage} - * - * @typedef SupportedLanguages - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.SupportedLanguages definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ -const SupportedLanguages = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * A single supported language response corresponds to information related - * to one supported language. - * - * @property {string} languageCode - * Supported language code, generally consisting of its ISO 639-1 - * identifier, for example, 'en', 'ja'. In certain cases, BCP-47 codes - * including language and region identifiers are returned (for example, - * 'zh-TW' and 'zh-CN') - * - * @property {string} displayName - * Human readable name of the language localized in the display language - * specified in the request. - * - * @property {boolean} supportSource - * Can be used as source language. - * - * @property {boolean} supportTarget - * Can be used as target language. - * - * @typedef SupportedLanguage - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.SupportedLanguage definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ -const SupportedLanguage = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * The Google Cloud Storage location for the input content. - * - * @property {string} inputUri - * Required. Source data URI. For example, `gs://my_bucket/my_object`. - * - * @typedef GcsSource - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.GcsSource definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ -const GcsSource = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * Input configuration for BatchTranslateText request. - * - * @property {string} mimeType - * Optional. Can be "text/plain" or "text/html". - * For `.tsv`, "text/html" is used if mime_type is missing. - * For `.html`, this field must be "text/html" or empty. - * For `.txt`, this field must be "text/plain" or empty. - * - * @property {Object} gcsSource - * Required. Google Cloud Storage location for the source input. - * This can be a single file (for example, - * `gs://translation-test/input.tsv`) or a wildcard (for example, - * `gs://translation-test/*`). If a file extension is `.tsv`, it can - * contain either one or two columns. The first column (optional) is the id - * of the text request. If the first column is missing, we use the row - * number (0-based) from the input file as the ID in the output file. The - * second column is the actual text to be - * translated. We recommend each row be <= 10K Unicode codepoints, - * otherwise an error might be returned. - * Note that the input tsv must be RFC 4180 compliant. - * - * You could use https://github.com/Clever/csvlint to check potential - * formatting errors in your tsv file. - * csvlint --delimiter='\t' your_input_file.tsv - * - * The other supported file extensions are `.txt` or `.html`, which is - * treated as a single large chunk of text. - * - * This object should have the same structure as [GcsSource]{@link google.cloud.translation.v3beta1.GcsSource} - * - * @typedef InputConfig - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.InputConfig definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ -const InputConfig = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * The Google Cloud Storage location for the output content. - * - * @property {string} outputUriPrefix - * Required. There must be no files under 'output_uri_prefix'. - * 'output_uri_prefix' must end with "/" and start with "gs://", otherwise an - * INVALID_ARGUMENT (400) error is returned. - * - * @typedef GcsDestination - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.GcsDestination definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ -const GcsDestination = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * Output configuration for BatchTranslateText request. - * - * @property {Object} gcsDestination - * Google Cloud Storage destination for output content. - * For every single input file (for example, gs://a/b/c.[extension]), we - * generate at most 2 * n output files. (n is the # of target_language_codes - * in the BatchTranslateTextRequest). - * - * Output files (tsv) generated are compliant with RFC 4180 except that - * record delimiters are '\n' instead of '\r\n'. We don't provide any way to - * change record delimiters. - * - * While the input files are being processed, we write/update an index file - * 'index.csv' under 'output_uri_prefix' (for example, - * gs://translation-test/index.csv) The index file is generated/updated as - * new files are being translated. The format is: - * - * input_file,target_language_code,translations_file,errors_file, - * glossary_translations_file,glossary_errors_file - * - * input_file is one file we matched using gcs_source.input_uri. - * target_language_code is provided in the request. - * translations_file contains the translations. (details provided below) - * errors_file contains the errors during processing of the file. (details - * below). Both translations_file and errors_file could be empty - * strings if we have no content to output. - * glossary_translations_file and glossary_errors_file are always empty - * strings if the input_file is tsv. They could also be empty if we have no - * content to output. - * - * Once a row is present in index.csv, the input/output matching never - * changes. Callers should also expect all the content in input_file are - * processed and ready to be consumed (that is, no partial output file is - * written). - * - * The format of translations_file (for target language code 'trg') is: - * gs://translation_test/a_b_c_'trg'_translations.[extension] - * - * If the input file extension is tsv, the output has the following - * columns: - * Column 1: ID of the request provided in the input, if it's not - * provided in the input, then the input row number is used (0-based). - * Column 2: source sentence. - * Column 3: translation without applying a glossary. Empty string if there - * is an error. - * Column 4 (only present if a glossary is provided in the request): - * translation after applying the glossary. Empty string if there is an - * error applying the glossary. Could be same string as column 3 if there is - * no glossary applied. - * - * If input file extension is a txt or html, the translation is directly - * written to the output file. If glossary is requested, a separate - * glossary_translations_file has format of - * gs://translation_test/a_b_c_'trg'_glossary_translations.[extension] - * - * The format of errors file (for target language code 'trg') is: - * gs://translation_test/a_b_c_'trg'_errors.[extension] - * - * If the input file extension is tsv, errors_file contains the following: - * Column 1: ID of the request provided in the input, if it's not - * provided in the input, then the input row number is used (0-based). - * Column 2: source sentence. - * Column 3: Error detail for the translation. Could be empty. - * Column 4 (only present if a glossary is provided in the request): - * Error when applying the glossary. - * - * If the input file extension is txt or html, glossary_error_file will be - * generated that contains error details. glossary_error_file has format of - * gs://translation_test/a_b_c_'trg'_glossary_errors.[extension] - * - * This object should have the same structure as [GcsDestination]{@link google.cloud.translation.v3beta1.GcsDestination} - * - * @typedef OutputConfig - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.OutputConfig definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ -const OutputConfig = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * The batch translation request. - * - * @property {string} 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. - * - * @property {string} sourceLanguageCode - * Required. Source language code. - * - * @property {string[]} targetLanguageCodes - * Required. Specify up to 10 language codes here. - * - * @property {Object.} 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. - * - * @property {Object[]} 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. - * - * This object should have the same structure as [InputConfig]{@link google.cloud.translation.v3beta1.InputConfig} - * - * @property {Object} 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. - * - * This object should have the same structure as [OutputConfig]{@link google.cloud.translation.v3beta1.OutputConfig} - * - * @property {Object.} glossaries - * Optional. Glossaries to be applied for translation. - * It's keyed by target language code. - * - * @property {Object.} 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. - * - * @typedef BatchTranslateTextRequest - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.BatchTranslateTextRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ -const BatchTranslateTextRequest = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * State metadata for the batch translation operation. - * - * @property {number} state - * The state of the operation. - * - * The number should be among the values of [State]{@link google.cloud.translation.v3beta1.State} - * - * @property {number} translatedCharacters - * Number of successfully translated characters so far (Unicode codepoints). - * - * @property {number} failedCharacters - * Number of characters that have failed to process so far (Unicode - * codepoints). - * - * @property {number} totalCharacters - * Total number of characters (Unicode codepoints). - * This is the total number of codepoints from input files times the number of - * target languages and appears here shortly after the call is submitted. - * - * @property {Object} submitTime - * Time when the operation was submitted. - * - * This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp} - * - * @typedef BatchTranslateMetadata - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.BatchTranslateMetadata definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ -const BatchTranslateMetadata = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * Stored in the google.longrunning.Operation.response field returned by - * BatchTranslateText if at least one sentence is translated successfully. - * - * @property {number} totalCharacters - * Total number of characters (Unicode codepoints). - * - * @property {number} translatedCharacters - * Number of successfully translated characters (Unicode codepoints). - * - * @property {number} failedCharacters - * Number of characters that have failed to process (Unicode codepoints). - * - * @property {Object} submitTime - * Time when the operation was submitted. - * - * This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp} - * - * @property {Object} endTime - * The time when the operation is finished and - * google.longrunning.Operation.done is set to true. - * - * This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp} - * - * @typedef BatchTranslateResponse - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.BatchTranslateResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ -const BatchTranslateResponse = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * Input configuration for glossaries. - * - * @property {Object} gcsSource - * Required. Google Cloud Storage location of glossary data. - * File format is determined based on the filename extension. API returns - * [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file - * formats. Wildcards are not allowed. This must be a single file in one of - * the following formats: - * - * For unidirectional glossaries: - * - * - TSV/CSV (`.tsv`/`.csv`): 2 column file, tab- or comma-separated. - * The first column is source text. The second column is target text. - * The file must not contain headers. That is, the first row is data, not - * column names. - * - * - TMX (`.tmx`): TMX file with parallel data defining source/target term - * pairs. - * - * For equivalent term sets glossaries: - * - * - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms - * in multiple languages. The format is defined for Google Translation - * Toolkit and documented in [Use a - * glossary](https://support.google.com/translatortoolkit/answer/6306379?hl=en). - * - * This object should have the same structure as [GcsSource]{@link google.cloud.translation.v3beta1.GcsSource} - * - * @typedef GlossaryInputConfig - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.GlossaryInputConfig definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ -const GlossaryInputConfig = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * Represents a glossary built from user provided data. - * - * @property {string} name - * Required. The resource name of the glossary. Glossary names have the form - * `projects/{project-id}/locations/{location-id}/glossaries/{glossary-id}`. - * - * @property {Object} languagePair - * Used with unidirectional glossaries. - * - * This object should have the same structure as [LanguageCodePair]{@link google.cloud.translation.v3beta1.LanguageCodePair} - * - * @property {Object} languageCodesSet - * Used with equivalent term set glossaries. - * - * This object should have the same structure as [LanguageCodesSet]{@link google.cloud.translation.v3beta1.LanguageCodesSet} - * - * @property {Object} inputConfig - * Required. Provides examples to build the glossary from. - * Total glossary must not exceed 10M Unicode codepoints. - * - * This object should have the same structure as [GlossaryInputConfig]{@link google.cloud.translation.v3beta1.GlossaryInputConfig} - * - * @property {number} entryCount - * Output only. The number of entries defined in the glossary. - * - * @property {Object} submitTime - * Output only. When CreateGlossary was called. - * - * This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp} - * - * @property {Object} endTime - * Output only. When the glossary creation was finished. - * - * This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp} - * - * @typedef Glossary - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.Glossary definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ -const Glossary = { - // This is for documentation. Actual contents will be loaded by gRPC. - - /** - * Used with unidirectional glossaries. - * - * @property {string} sourceLanguageCode - * Required. The BCP-47 language code of the input text, for example, - * "en-US". Expected to be an exact match for GlossaryTerm.language_code. - * - * @property {string} targetLanguageCode - * Required. The BCP-47 language code for translation output, for example, - * "zh-CN". Expected to be an exact match for GlossaryTerm.language_code. - * - * @typedef LanguageCodePair - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.Glossary.LanguageCodePair definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ - LanguageCodePair: { - // This is for documentation. Actual contents will be loaded by gRPC. - }, - - /** - * Used with equivalent term set glossaries. - * - * @property {string[]} languageCodes - * The BCP-47 language code(s) for terms defined in the glossary. - * All entries are unique. The list contains at least two entries. - * Expected to be an exact match for GlossaryTerm.language_code. - * - * @typedef LanguageCodesSet - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.Glossary.LanguageCodesSet definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ - LanguageCodesSet: { - // This is for documentation. Actual contents will be loaded by gRPC. - } -}; - -/** - * Request message for CreateGlossary. - * - * @property {string} parent - * Required. The project name. - * - * @property {Object} glossary - * Required. The glossary to create. - * - * This object should have the same structure as [Glossary]{@link google.cloud.translation.v3beta1.Glossary} - * - * @typedef CreateGlossaryRequest - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.CreateGlossaryRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ -const CreateGlossaryRequest = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * Request message for GetGlossary. - * - * @property {string} name - * Required. The name of the glossary to retrieve. - * - * @typedef GetGlossaryRequest - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.GetGlossaryRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ -const GetGlossaryRequest = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * Request message for DeleteGlossary. - * - * @property {string} name - * Required. The name of the glossary to delete. - * - * @typedef DeleteGlossaryRequest - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.DeleteGlossaryRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ -const DeleteGlossaryRequest = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * Request message for ListGlossaries. - * - * @property {string} parent - * Required. The name of the project from which to list all of the glossaries. - * - * @property {number} pageSize - * Optional. Requested page size. The server may return fewer glossaries than - * requested. If unspecified, the server picks an appropriate default. - * - * @property {string} 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. - * - * @property {string} 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. - * - * @typedef ListGlossariesRequest - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.ListGlossariesRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ -const ListGlossariesRequest = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * Response message for ListGlossaries. - * - * @property {Object[]} glossaries - * The list of glossaries for a project. - * - * This object should have the same structure as [Glossary]{@link google.cloud.translation.v3beta1.Glossary} - * - * @property {string} nextPageToken - * A token to retrieve a page of results. Pass this value in the - * [ListGlossariesRequest.page_token] field in the subsequent call to - * `ListGlossaries` method to retrieve the next page of results. - * - * @typedef ListGlossariesResponse - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.ListGlossariesResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ -const ListGlossariesResponse = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * Stored in the google.longrunning.Operation.metadata field returned by - * CreateGlossary. - * - * @property {string} name - * The name of the glossary that is being created. - * - * @property {number} state - * The current state of the glossary creation operation. - * - * The number should be among the values of [State]{@link google.cloud.translation.v3beta1.State} - * - * @property {Object} submitTime - * The time when the operation was submitted to the server. - * - * This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp} - * - * @typedef CreateGlossaryMetadata - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.CreateGlossaryMetadata definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ -const CreateGlossaryMetadata = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * Stored in the google.longrunning.Operation.metadata field returned by - * DeleteGlossary. - * - * @property {string} name - * The name of the glossary that is being deleted. - * - * @property {number} state - * The current state of the glossary deletion operation. - * - * The number should be among the values of [State]{@link google.cloud.translation.v3beta1.State} - * - * @property {Object} submitTime - * The time when the operation was submitted to the server. - * - * This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp} - * - * @typedef DeleteGlossaryMetadata - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.DeleteGlossaryMetadata definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ -const DeleteGlossaryMetadata = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * Stored in the google.longrunning.Operation.response field returned by - * DeleteGlossary. - * - * @property {string} name - * The name of the deleted glossary. - * - * @property {Object} submitTime - * The time when the operation was submitted to the server. - * - * This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp} - * - * @property {Object} endTime - * The time when the glossary deletion is finished and - * google.longrunning.Operation.done is set to true. - * - * This object should have the same structure as [Timestamp]{@link google.protobuf.Timestamp} - * - * @typedef DeleteGlossaryResponse - * @memberof google.cloud.translation.v3beta1 - * @see [google.cloud.translation.v3beta1.DeleteGlossaryResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/cloud/translate/v3beta1/translation_service.proto} - */ -const DeleteGlossaryResponse = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; \ No newline at end of file diff --git a/src/v3beta1/doc/google/longrunning/doc_operations.js b/src/v3beta1/doc/google/longrunning/doc_operations.js deleted file mode 100644 index 4719aebd..00000000 --- a/src/v3beta1/doc/google/longrunning/doc_operations.js +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2019 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Note: this file is purely for documentation. Any contents are not expected -// to be loaded as the JS file. - -/** - * This resource represents a long-running operation that is the result of a - * network API call. - * - * @property {string} name - * The server-assigned name, which is only unique within the same service that - * originally returns it. If you use the default HTTP mapping, the - * `name` should have the format of `operations/some/unique/name`. - * - * @property {Object} metadata - * Service-specific metadata associated with the operation. It typically - * contains progress information and common metadata such as create time. - * Some services might not provide such metadata. Any method that returns a - * long-running operation should document the metadata type, if any. - * - * This object should have the same structure as [Any]{@link google.protobuf.Any} - * - * @property {boolean} done - * If the value is `false`, it means the operation is still in progress. - * If `true`, the operation is completed, and either `error` or `response` is - * available. - * - * @property {Object} error - * The error result of the operation in case of failure or cancellation. - * - * This object should have the same structure as [Status]{@link google.rpc.Status} - * - * @property {Object} response - * The normal response of the operation in case of success. If the original - * method returns no data on success, such as `Delete`, the response is - * `google.protobuf.Empty`. If the original method is standard - * `Get`/`Create`/`Update`, the response should be the resource. For other - * methods, the response should have the type `XxxResponse`, where `Xxx` - * is the original method name. For example, if the original method name - * is `TakeSnapshot()`, the inferred response type is - * `TakeSnapshotResponse`. - * - * This object should have the same structure as [Any]{@link google.protobuf.Any} - * - * @typedef Operation - * @memberof google.longrunning - * @see [google.longrunning.Operation definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/longrunning/operations.proto} - */ -const Operation = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; \ No newline at end of file diff --git a/src/v3beta1/doc/google/protobuf/doc_any.js b/src/v3beta1/doc/google/protobuf/doc_any.js deleted file mode 100644 index cdd2fc80..00000000 --- a/src/v3beta1/doc/google/protobuf/doc_any.js +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright 2019 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Note: this file is purely for documentation. Any contents are not expected -// to be loaded as the JS file. - -/** - * `Any` contains an arbitrary serialized protocol buffer message along with a - * URL that describes the type of the serialized message. - * - * Protobuf library provides support to pack/unpack Any values in the form - * of utility functions or additional generated methods of the Any type. - * - * Example 1: Pack and unpack a message in C++. - * - * Foo foo = ...; - * Any any; - * any.PackFrom(foo); - * ... - * if (any.UnpackTo(&foo)) { - * ... - * } - * - * Example 2: Pack and unpack a message in Java. - * - * Foo foo = ...; - * Any any = Any.pack(foo); - * ... - * if (any.is(Foo.class)) { - * foo = any.unpack(Foo.class); - * } - * - * Example 3: Pack and unpack a message in Python. - * - * foo = Foo(...) - * any = Any() - * any.Pack(foo) - * ... - * if any.Is(Foo.DESCRIPTOR): - * any.Unpack(foo) - * ... - * - * Example 4: Pack and unpack a message in Go - * - * foo := &pb.Foo{...} - * any, err := ptypes.MarshalAny(foo) - * ... - * foo := &pb.Foo{} - * if err := ptypes.UnmarshalAny(any, foo); err != nil { - * ... - * } - * - * The pack methods provided by protobuf library will by default use - * 'type.googleapis.com/full.type.name' as the type URL and the unpack - * methods only use the fully qualified type name after the last '/' - * in the type URL, for example "foo.bar.com/x/y.z" will yield type - * name "y.z". - * - * - * # JSON - * - * The JSON representation of an `Any` value uses the regular - * representation of the deserialized, embedded message, with an - * additional field `@type` which contains the type URL. Example: - * - * package google.profile; - * message Person { - * string first_name = 1; - * string last_name = 2; - * } - * - * { - * "@type": "type.googleapis.com/google.profile.Person", - * "firstName": , - * "lastName": - * } - * - * If the embedded message type is well-known and has a custom JSON - * representation, that representation will be embedded adding a field - * `value` which holds the custom JSON in addition to the `@type` - * field. Example (for message google.protobuf.Duration): - * - * { - * "@type": "type.googleapis.com/google.protobuf.Duration", - * "value": "1.212s" - * } - * - * @property {string} typeUrl - * A URL/resource name that uniquely identifies the type of the serialized - * protocol buffer message. This string must contain at least - * one "/" character. The last segment of the URL's path must represent - * the fully qualified name of the type (as in - * `path/google.protobuf.Duration`). The name should be in a canonical form - * (e.g., leading "." is not accepted). - * - * In practice, teams usually precompile into the binary all types that they - * expect it to use in the context of Any. However, for URLs which use the - * scheme `http`, `https`, or no scheme, one can optionally set up a type - * server that maps type URLs to message definitions as follows: - * - * * If no scheme is provided, `https` is assumed. - * * An HTTP GET on the URL must yield a google.protobuf.Type - * value in binary format, or produce an error. - * * Applications are allowed to cache lookup results based on the - * URL, or have them precompiled into a binary to avoid any - * lookup. Therefore, binary compatibility needs to be preserved - * on changes to types. (Use versioned type names to manage - * breaking changes.) - * - * Note: this functionality is not currently available in the official - * protobuf release, and it is not used for type URLs beginning with - * type.googleapis.com. - * - * Schemes other than `http`, `https` (or the empty scheme) might be - * used with implementation specific semantics. - * - * @property {Buffer} value - * Must be a valid serialized protocol buffer of the above specified type. - * - * @typedef Any - * @memberof google.protobuf - * @see [google.protobuf.Any definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/any.proto} - */ -const Any = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; \ No newline at end of file diff --git a/src/v3beta1/doc/google/protobuf/doc_timestamp.js b/src/v3beta1/doc/google/protobuf/doc_timestamp.js deleted file mode 100644 index c457acc0..00000000 --- a/src/v3beta1/doc/google/protobuf/doc_timestamp.js +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2019 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Note: this file is purely for documentation. Any contents are not expected -// to be loaded as the JS file. - -/** - * A Timestamp represents a point in time independent of any time zone or local - * calendar, encoded as a count of seconds and fractions of seconds at - * nanosecond resolution. The count is relative to an epoch at UTC midnight on - * January 1, 1970, in the proleptic Gregorian calendar which extends the - * Gregorian calendar backwards to year one. - * - * All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap - * second table is needed for interpretation, using a [24-hour linear - * smear](https://developers.google.com/time/smear). - * - * The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By - * restricting to that range, we ensure that we can convert to and from [RFC - * 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings. - * - * # Examples - * - * Example 1: Compute Timestamp from POSIX `time()`. - * - * Timestamp timestamp; - * timestamp.set_seconds(time(NULL)); - * timestamp.set_nanos(0); - * - * Example 2: Compute Timestamp from POSIX `gettimeofday()`. - * - * struct timeval tv; - * gettimeofday(&tv, NULL); - * - * Timestamp timestamp; - * timestamp.set_seconds(tv.tv_sec); - * timestamp.set_nanos(tv.tv_usec * 1000); - * - * Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. - * - * FILETIME ft; - * GetSystemTimeAsFileTime(&ft); - * UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; - * - * // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z - * // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. - * Timestamp timestamp; - * timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); - * timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); - * - * Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. - * - * long millis = System.currentTimeMillis(); - * - * Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) - * .setNanos((int) ((millis % 1000) * 1000000)).build(); - * - * - * Example 5: Compute Timestamp from current time in Python. - * - * timestamp = Timestamp() - * timestamp.GetCurrentTime() - * - * # JSON Mapping - * - * In JSON format, the Timestamp type is encoded as a string in the - * [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the - * format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" - * where {year} is always expressed using four digits while {month}, {day}, - * {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional - * seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), - * are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone - * is required. A proto3 JSON serializer should always use UTC (as indicated by - * "Z") when printing the Timestamp type and a proto3 JSON parser should be - * able to accept both UTC and other timezones (as indicated by an offset). - * - * For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past - * 01:30 UTC on January 15, 2017. - * - * In JavaScript, one can convert a Date object to this format using the - * standard - * [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) - * method. In Python, a standard `datetime.datetime` object can be converted - * to this format using - * [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with - * the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use - * the Joda Time's [`ISODateTimeFormat.dateTime()`](https://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime%2D%2D) to obtain a formatter capable of generating timestamps in this format. - * - * @property {number} seconds - * Represents seconds of UTC time since Unix epoch - * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to - * 9999-12-31T23:59:59Z inclusive. - * - * @property {number} nanos - * Non-negative fractions of a second at nanosecond resolution. Negative - * second values with fractions must still have non-negative nanos values - * that count forward in time. Must be from 0 to 999,999,999 - * inclusive. - * - * @typedef Timestamp - * @memberof google.protobuf - * @see [google.protobuf.Timestamp definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto} - */ -const Timestamp = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; \ No newline at end of file diff --git a/src/v3beta1/doc/google/rpc/doc_status.js b/src/v3beta1/doc/google/rpc/doc_status.js deleted file mode 100644 index 432ab6bb..00000000 --- a/src/v3beta1/doc/google/rpc/doc_status.js +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright 2019 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Note: this file is purely for documentation. Any contents are not expected -// to be loaded as the JS file. - -/** - * The `Status` type defines a logical error model that is suitable for - * different programming environments, including REST APIs and RPC APIs. It is - * used by [gRPC](https://github.com/grpc). The error model is designed to be: - * - * - Simple to use and understand for most users - * - Flexible enough to meet unexpected needs - * - * # Overview - * - * The `Status` message contains three pieces of data: error code, error - * message, and error details. The error code should be an enum value of - * google.rpc.Code, but it may accept additional error codes - * if needed. The error message should be a developer-facing English message - * that helps developers *understand* and *resolve* the error. If a localized - * user-facing error message is needed, put the localized message in the error - * details or localize it in the client. The optional error details may contain - * arbitrary information about the error. There is a predefined set of error - * detail types in the package `google.rpc` that can be used for common error - * conditions. - * - * # Language mapping - * - * The `Status` message is the logical representation of the error model, but it - * is not necessarily the actual wire format. When the `Status` message is - * exposed in different client libraries and different wire protocols, it can be - * mapped differently. For example, it will likely be mapped to some exceptions - * in Java, but more likely mapped to some error codes in C. - * - * # Other uses - * - * The error model and the `Status` message can be used in a variety of - * environments, either with or without APIs, to provide a - * consistent developer experience across different environments. - * - * Example uses of this error model include: - * - * - Partial errors. If a service needs to return partial errors to the client, - * it may embed the `Status` in the normal response to indicate the partial - * errors. - * - * - Workflow errors. A typical workflow has multiple steps. Each step may - * have a `Status` message for error reporting. - * - * - Batch operations. If a client uses batch request and batch response, the - * `Status` message should be used directly inside batch response, one for - * each error sub-response. - * - * - Asynchronous operations. If an API call embeds asynchronous operation - * results in its response, the status of those operations should be - * represented directly using the `Status` message. - * - * - Logging. If some API errors are stored in logs, the message `Status` could - * be used directly after any stripping needed for security/privacy reasons. - * - * @property {number} code - * The status code, which should be an enum value of - * google.rpc.Code. - * - * @property {string} message - * A developer-facing error message, which should be in English. Any - * user-facing error message should be localized and sent in the - * google.rpc.Status.details field, or localized - * by the client. - * - * @property {Object[]} details - * A list of messages that carry the error details. There is a common set of - * message types for APIs to use. - * - * This object should have the same structure as [Any]{@link google.protobuf.Any} - * - * @typedef Status - * @memberof google.rpc - * @see [google.rpc.Status definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/rpc/status.proto} - */ -const Status = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; \ No newline at end of file diff --git a/src/v3beta1/index.js b/src/v3beta1/index.ts similarity index 68% rename from src/v3beta1/index.js rename to src/v3beta1/index.ts index 2ee97b83..07f3c18e 100644 --- a/src/v3beta1/index.js +++ b/src/v3beta1/index.ts @@ -11,9 +11,9 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** -'use strict'; - -const TranslationServiceClient = require('./translation_service_client'); - -module.exports.TranslationServiceClient = TranslationServiceClient; +export {TranslationServiceClient} from './translation_service_client'; diff --git a/src/v3beta1/translation_service_client.js b/src/v3beta1/translation_service_client.ts similarity index 50% rename from src/v3beta1/translation_service_client.js rename to src/v3beta1/translation_service_client.ts index bb5c9585..04455605 100644 --- a/src/v3beta1/translation_service_client.js +++ b/src/v3beta1/translation_service_client.ts @@ -11,22 +11,43 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** -'use strict'; +import * as gax from 'google-gax'; +import { + APICallback, + Callback, + CallOptions, + Descriptors, + ClientOptions, + LROperation, + PaginationCallback, + PaginationResponse, +} from 'google-gax'; +import * as path from 'path'; -const gapicConfig = require('./translation_service_client_config.json'); -const gax = require('google-gax'); -const path = require('path'); +import {Transform} from 'stream'; +import * as protosTypes from '../../protos/protos'; +import * as gapicConfig from './translation_service_client_config.json'; -const VERSION = require('../../../package.json').version; +const version = require('../../../package.json').version; /** - * Provides natural language translation operations. - * + * Provides natural language translation operations. * @class * @memberof v3beta1 */ -class TranslationServiceClient { +export class TranslationServiceClient { + private _descriptors: Descriptors = {page: {}, stream: {}, longrunning: {}}; + private _translationServiceStub: Promise<{[name: string]: Function}>; + private _innerApiCalls: {[name: string]: Function}; + private _pathTemplates: {[name: string]: gax.PathTemplate}; + private _terminated = false; + auth: gax.GoogleAuth; + /** * Construct an instance of TranslationServiceClient. * @@ -54,58 +75,55 @@ class TranslationServiceClient { * @param {string} [options.apiEndpoint] - The domain name of the * API remote host. */ - constructor(opts) { - opts = opts || {}; - this._descriptors = {}; - if (global.isBrowser) { - // If we're in browser, we use gRPC fallback. - opts.fallback = true; + constructor(opts?: ClientOptions) { + // Ensure that options include the service address and port. + const staticMembers = this.constructor as typeof TranslationServiceClient; + const servicePath = + opts && opts.servicePath + ? opts.servicePath + : opts && opts.apiEndpoint + ? opts.apiEndpoint + : staticMembers.servicePath; + const port = opts && opts.port ? opts.port : staticMembers.port; + + if (!opts) { + opts = {servicePath, port}; } + opts.servicePath = opts.servicePath || servicePath; + opts.port = opts.port || port; + opts.clientConfig = opts.clientConfig || {}; + const isBrowser = typeof window !== 'undefined'; + if (isBrowser) { + opts.fallback = true; + } // If we are in browser, we are already using fallback because of the // "browser" field in package.json. // But if we were explicitly requested to use fallback, let's do it now. - const gaxModule = !global.isBrowser && opts.fallback ? gax.fallback : gax; - - const servicePath = - opts.servicePath || opts.apiEndpoint || this.constructor.servicePath; - - // Ensure that options include the service address and port. - opts = Object.assign( - { - clientConfig: {}, - port: this.constructor.port, - servicePath, - }, - opts - ); + const gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; // Create a `gaxGrpc` object, with any grpc-specific options // sent to the client. - opts.scopes = this.constructor.scopes; + opts.scopes = (this.constructor as typeof TranslationServiceClient).scopes; const gaxGrpc = new gaxModule.GrpcClient(opts); // Save the auth object to the client, for use by other methods. - this.auth = gaxGrpc.auth; + this.auth = gaxGrpc.auth as gax.GoogleAuth; // Determine the client header string. - const clientHeader = []; - + const clientHeader = [`gax/${gaxModule.version}`, `gapic/${version}`]; if (typeof process !== 'undefined' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); - } - clientHeader.push(`gax/${gaxModule.version}`); - if (opts.fallback) { - clientHeader.push(`gl-web/${gaxModule.version}`); } else { + clientHeader.push(`gl-web/${gaxModule.version}`); + } + if (!opts.fallback) { clientHeader.push(`grpc/${gaxGrpc.grpcVersion}`); } - clientHeader.push(`gapic/${VERSION}`); if (opts.libName && opts.libVersion) { clientHeader.push(`${opts.libName}/${opts.libVersion}`); } - // Load the applicable protos. // For Node.js, pass the path to JSON proto file. // For browsers, pass the JSON content. @@ -125,12 +143,12 @@ class TranslationServiceClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this._pathTemplates = { - glossaryPathTemplate: new gaxModule.PathTemplate( - 'projects/{project}/locations/{location}/glossaries/{glossary}' - ), locationPathTemplate: new gaxModule.PathTemplate( 'projects/{project}/locations/{location}' ), + glossaryPathTemplate: new gaxModule.PathTemplate( + 'projects/{project}/locations/{location}/glossaries/{glossary}' + ), }; // Some of the methods on this service return "paged" results, @@ -144,50 +162,51 @@ class TranslationServiceClient { ), }; - const protoFilesRoot = opts.fallback - ? gaxModule.protobuf.Root.fromJSON(require('../../protos/protos.json')) - : gaxModule.protobuf.loadSync(nodejsProtoPath); - // 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. - this.operationsClient = new gaxModule.lro({ - auth: gaxGrpc.auth, - grpc: gaxGrpc.grpc, - }).operationsClient(opts); + const protoFilesRoot = opts.fallback + ? gaxModule.protobuf.Root.fromJSON(require('../../protos/protos.json')) + : gaxModule.protobuf.loadSync(nodejsProtoPath); + const operationsClient = gaxModule + .lro({ + auth: this.auth, + grpc: 'grpc' in gaxGrpc ? gaxGrpc.grpc : undefined, + }) + .operationsClient(opts); const batchTranslateTextResponse = protoFilesRoot.lookup( - 'google.cloud.translation.v3beta1.BatchTranslateResponse' - ); + '.google.cloud.translation.v3beta1.BatchTranslateResponse' + ) as gax.protobuf.Type; const batchTranslateTextMetadata = protoFilesRoot.lookup( - 'google.cloud.translation.v3beta1.BatchTranslateMetadata' - ); + '.google.cloud.translation.v3beta1.BatchTranslateMetadata' + ) as gax.protobuf.Type; const createGlossaryResponse = protoFilesRoot.lookup( - 'google.cloud.translation.v3beta1.Glossary' - ); + '.google.cloud.translation.v3beta1.Glossary' + ) as gax.protobuf.Type; const createGlossaryMetadata = protoFilesRoot.lookup( - 'google.cloud.translation.v3beta1.CreateGlossaryMetadata' - ); + '.google.cloud.translation.v3beta1.CreateGlossaryMetadata' + ) as gax.protobuf.Type; const deleteGlossaryResponse = protoFilesRoot.lookup( - 'google.cloud.translation.v3beta1.DeleteGlossaryResponse' - ); + '.google.cloud.translation.v3beta1.DeleteGlossaryResponse' + ) as gax.protobuf.Type; const deleteGlossaryMetadata = protoFilesRoot.lookup( - 'google.cloud.translation.v3beta1.DeleteGlossaryMetadata' - ); + '.google.cloud.translation.v3beta1.DeleteGlossaryMetadata' + ) as gax.protobuf.Type; this._descriptors.longrunning = { batchTranslateText: new gaxModule.LongrunningDescriptor( - this.operationsClient, + operationsClient, batchTranslateTextResponse.decode.bind(batchTranslateTextResponse), batchTranslateTextMetadata.decode.bind(batchTranslateTextMetadata) ), createGlossary: new gaxModule.LongrunningDescriptor( - this.operationsClient, + operationsClient, createGlossaryResponse.decode.bind(createGlossaryResponse), createGlossaryMetadata.decode.bind(createGlossaryMetadata) ), deleteGlossary: new gaxModule.LongrunningDescriptor( - this.operationsClient, + operationsClient, deleteGlossaryResponse.decode.bind(deleteGlossaryResponse), deleteGlossaryMetadata.decode.bind(deleteGlossaryMetadata) ), @@ -196,8 +215,8 @@ class TranslationServiceClient { // Put together the default options sent with requests. const defaults = gaxGrpc.constructSettings( 'google.cloud.translation.v3beta1.TranslationService', - gapicConfig, - opts.clientConfig, + gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')} ); @@ -208,14 +227,15 @@ class TranslationServiceClient { // Put together the "service stub" for // google.cloud.translation.v3beta1.TranslationService. - const translationServiceStub = gaxGrpc.createStub( + this._translationServiceStub = gaxGrpc.createStub( opts.fallback - ? protos.lookupService( + ? (protos as protobuf.Root).lookupService( 'google.cloud.translation.v3beta1.TranslationService' ) - : protos.google.cloud.translation.v3beta1.TranslationService, + : // tslint:disable-next-line no-any + (protos as any).google.cloud.translation.v3beta1.TranslationService, opts - ); + ) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -229,21 +249,35 @@ class TranslationServiceClient { 'getGlossary', 'deleteGlossary', ]; + for (const methodName of translationServiceStubMethods) { - const innerCallPromise = translationServiceStub.then( - stub => (...args) => { + const innerCallPromise = this._translationServiceStub.then( + stub => (...args: Array<{}>) => { return stub[methodName].apply(stub, args); }, - err => () => { + (err: Error | null | undefined) => () => { throw err; } ); - this._innerApiCalls[methodName] = gaxModule.createApiCall( + + const apiCall = gaxModule.createApiCall( innerCallPromise, defaults[methodName], this._descriptors.page[methodName] || + this._descriptors.stream[methodName] || this._descriptors.longrunning[methodName] ); + + this._innerApiCalls[methodName] = ( + argument: {}, + callOptions?: CallOptions, + callback?: APICallback + ) => { + if (this._terminated) { + return Promise.reject('The client has already been closed.'); + } + return apiCall(argument, callOptions, callback); + }; } } @@ -280,19 +314,49 @@ class TranslationServiceClient { ]; } + getProjectId(): Promise; + getProjectId(callback: Callback): void; /** * Return the project ID used by this class. * @param {function(Error, string)} callback - the callback to * be called with the current project Id. */ - getProjectId(callback) { - return this.auth.getProjectId(callback); + getProjectId( + callback?: Callback + ): Promise | void { + if (callback) { + this.auth.getProjectId(callback); + return; + } + return this.auth.getProjectId(); } // ------------------- // -- Service calls -- // ------------------- - + translateText( + request: protosTypes.google.cloud.translation.v3beta1.ITranslateTextRequest, + options?: gax.CallOptions + ): Promise< + [ + protosTypes.google.cloud.translation.v3beta1.ITranslateTextResponse, + ( + | protosTypes.google.cloud.translation.v3beta1.ITranslateTextRequest + | undefined + ), + {} | undefined + ] + >; + translateText( + request: protosTypes.google.cloud.translation.v3beta1.ITranslateTextRequest, + options: gax.CallOptions, + callback: Callback< + protosTypes.google.cloud.translation.v3beta1.ITranslateTextResponse, + | protosTypes.google.cloud.translation.v3beta1.ITranslateTextRequest + | undefined, + {} | undefined + > + ): void; /** * Translates input text and returns translated text. * @@ -302,6 +366,15 @@ class TranslationServiceClient { * 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. @@ -320,15 +393,6 @@ class TranslationServiceClient { * * Models and glossaries must be within the same region (have same * location-id), otherwise an INVALID_ARGUMENT (400) error is returned. - * @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.model] * Optional. The `model` type requested for this translation. * @@ -347,13 +411,11 @@ class TranslationServiceClient { * `projects/{project-id}/locations/global/models/general/nmt`. * * If missing, the system decides which google base model to use. - * @param {Object} [request.glossaryConfig] + * @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. - * - * This object should have the same structure as [TranslateTextGlossaryConfig]{@link google.cloud.translation.v3beta1.TranslateTextGlossaryConfig} - * @param {Object.} [request.labels] + * @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 @@ -362,60 +424,79 @@ class TranslationServiceClient { * 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] - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html} 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 [TranslateTextResponse]{@link google.cloud.translation.v3beta1.TranslateTextResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing [TranslateTextResponse]{@link google.cloud.translation.v3beta1.TranslateTextResponse}. * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * const translate = require('@google-cloud/translate'); - * - * const client = new translate.v3beta1.TranslationServiceClient({ - * // optional auth parameters. - * }); - * - * const contents = []; - * const targetLanguageCode = ''; - * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); - * const request = { - * contents: contents, - * targetLanguageCode: targetLanguageCode, - * parent: formattedParent, - * }; - * client.translateText(request) - * .then(responses => { - * const response = responses[0]; - * // doThingsWith(response) - * }) - * .catch(err => { - * console.error(err); - * }); */ - translateText(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; + translateText( + request: protosTypes.google.cloud.translation.v3beta1.ITranslateTextRequest, + optionsOrCallback?: + | gax.CallOptions + | Callback< + protosTypes.google.cloud.translation.v3beta1.ITranslateTextResponse, + | protosTypes.google.cloud.translation.v3beta1.ITranslateTextRequest + | undefined, + {} | undefined + >, + callback?: Callback< + protosTypes.google.cloud.translation.v3beta1.ITranslateTextResponse, + | protosTypes.google.cloud.translation.v3beta1.ITranslateTextRequest + | undefined, + {} | undefined + > + ): Promise< + [ + protosTypes.google.cloud.translation.v3beta1.ITranslateTextResponse, + ( + | protosTypes.google.cloud.translation.v3beta1.ITranslateTextRequest + | undefined + ), + {} | undefined + ] + > | void { + request = request || {}; + let options: gax.CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; options = {}; + } else { + options = optionsOrCallback as gax.CallOptions; } - request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers[ 'x-goog-request-params' ] = gax.routingHeader.fromParams({ - parent: request.parent, + parent: request.parent || '', }); - return this._innerApiCalls.translateText(request, options, callback); } - + detectLanguage( + request: protosTypes.google.cloud.translation.v3beta1.IDetectLanguageRequest, + options?: gax.CallOptions + ): Promise< + [ + protosTypes.google.cloud.translation.v3beta1.IDetectLanguageResponse, + ( + | protosTypes.google.cloud.translation.v3beta1.IDetectLanguageRequest + | undefined + ), + {} | undefined + ] + >; + detectLanguage( + request: protosTypes.google.cloud.translation.v3beta1.IDetectLanguageRequest, + options: gax.CallOptions, + callback: Callback< + protosTypes.google.cloud.translation.v3beta1.IDetectLanguageResponse, + | protosTypes.google.cloud.translation.v3beta1.IDetectLanguageRequest + | undefined, + {} | undefined + > + ): void; /** * Detects the language of text within a request. * @@ -443,12 +524,12 @@ class TranslationServiceClient { * `projects/{project-id}/locations/{location-id}/models/language-detection/default`. * * If not specified, the default model is used. - * @param {string} [request.content] + * @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 {Object.} [request.labels] + * @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 @@ -457,53 +538,79 @@ class TranslationServiceClient { * 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] - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html} 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 [DetectLanguageResponse]{@link google.cloud.translation.v3beta1.DetectLanguageResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing [DetectLanguageResponse]{@link google.cloud.translation.v3beta1.DetectLanguageResponse}. * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * const translate = require('@google-cloud/translate'); - * - * const client = new translate.v3beta1.TranslationServiceClient({ - * // optional auth parameters. - * }); - * - * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); - * client.detectLanguage({parent: formattedParent}) - * .then(responses => { - * const response = responses[0]; - * // doThingsWith(response) - * }) - * .catch(err => { - * console.error(err); - * }); */ - detectLanguage(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; + detectLanguage( + request: protosTypes.google.cloud.translation.v3beta1.IDetectLanguageRequest, + optionsOrCallback?: + | gax.CallOptions + | Callback< + protosTypes.google.cloud.translation.v3beta1.IDetectLanguageResponse, + | protosTypes.google.cloud.translation.v3beta1.IDetectLanguageRequest + | undefined, + {} | undefined + >, + callback?: Callback< + protosTypes.google.cloud.translation.v3beta1.IDetectLanguageResponse, + | protosTypes.google.cloud.translation.v3beta1.IDetectLanguageRequest + | undefined, + {} | undefined + > + ): Promise< + [ + protosTypes.google.cloud.translation.v3beta1.IDetectLanguageResponse, + ( + | protosTypes.google.cloud.translation.v3beta1.IDetectLanguageRequest + | undefined + ), + {} | undefined + ] + > | void { + request = request || {}; + let options: gax.CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; options = {}; + } else { + options = optionsOrCallback as gax.CallOptions; } - request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers[ 'x-goog-request-params' ] = gax.routingHeader.fromParams({ - parent: request.parent, + parent: request.parent || '', }); - return this._innerApiCalls.detectLanguage(request, options, callback); } - + getSupportedLanguages( + request: protosTypes.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest, + options?: gax.CallOptions + ): Promise< + [ + protosTypes.google.cloud.translation.v3beta1.ISupportedLanguages, + ( + | protosTypes.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + | undefined + ), + {} | undefined + ] + >; + getSupportedLanguages( + request: protosTypes.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest, + options: gax.CallOptions, + callback: Callback< + protosTypes.google.cloud.translation.v3beta1.ISupportedLanguages, + | protosTypes.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + | undefined, + {} | undefined + > + ): void; /** * Returns a list of supported languages for translation. * @@ -542,57 +649,167 @@ class TranslationServiceClient { * * Returns languages supported by the specified model. * If missing, we get supported languages of Google general base (PBMT) model. - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html} 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 [SupportedLanguages]{@link google.cloud.translation.v3beta1.SupportedLanguages}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing [SupportedLanguages]{@link google.cloud.translation.v3beta1.SupportedLanguages}. * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * const translate = require('@google-cloud/translate'); - * - * const client = new translate.v3beta1.TranslationServiceClient({ - * // optional auth parameters. - * }); - * - * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); - * client.getSupportedLanguages({parent: formattedParent}) - * .then(responses => { - * const response = responses[0]; - * // doThingsWith(response) - * }) - * .catch(err => { - * console.error(err); - * }); */ - getSupportedLanguages(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; + getSupportedLanguages( + request: protosTypes.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest, + optionsOrCallback?: + | gax.CallOptions + | Callback< + protosTypes.google.cloud.translation.v3beta1.ISupportedLanguages, + | protosTypes.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + | undefined, + {} | undefined + >, + callback?: Callback< + protosTypes.google.cloud.translation.v3beta1.ISupportedLanguages, + | protosTypes.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + | undefined, + {} | undefined + > + ): Promise< + [ + protosTypes.google.cloud.translation.v3beta1.ISupportedLanguages, + ( + | protosTypes.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + | undefined + ), + {} | undefined + ] + > | void { + request = request || {}; + let options: gax.CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; options = {}; + } else { + options = optionsOrCallback as gax.CallOptions; } - request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers[ 'x-goog-request-params' ] = gax.routingHeader.fromParams({ - parent: request.parent, + parent: request.parent || '', }); - return this._innerApiCalls.getSupportedLanguages( request, options, callback ); } + getGlossary( + request: protosTypes.google.cloud.translation.v3beta1.IGetGlossaryRequest, + options?: gax.CallOptions + ): Promise< + [ + protosTypes.google.cloud.translation.v3beta1.IGlossary, + ( + | protosTypes.google.cloud.translation.v3beta1.IGetGlossaryRequest + | undefined + ), + {} | undefined + ] + >; + getGlossary( + request: protosTypes.google.cloud.translation.v3beta1.IGetGlossaryRequest, + options: gax.CallOptions, + callback: Callback< + protosTypes.google.cloud.translation.v3beta1.IGlossary, + | protosTypes.google.cloud.translation.v3beta1.IGetGlossaryRequest + | undefined, + {} | undefined + > + ): void; + /** + * 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 [Glossary]{@link google.cloud.translation.v3beta1.Glossary}. + * The promise has a method named "cancel" which cancels the ongoing API call. + */ + getGlossary( + request: protosTypes.google.cloud.translation.v3beta1.IGetGlossaryRequest, + optionsOrCallback?: + | gax.CallOptions + | Callback< + protosTypes.google.cloud.translation.v3beta1.IGlossary, + | protosTypes.google.cloud.translation.v3beta1.IGetGlossaryRequest + | undefined, + {} | undefined + >, + callback?: Callback< + protosTypes.google.cloud.translation.v3beta1.IGlossary, + | protosTypes.google.cloud.translation.v3beta1.IGetGlossaryRequest + | undefined, + {} | undefined + > + ): Promise< + [ + protosTypes.google.cloud.translation.v3beta1.IGlossary, + ( + | protosTypes.google.cloud.translation.v3beta1.IGetGlossaryRequest + | undefined + ), + {} | undefined + ] + > | void { + request = request || {}; + 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' + ] = gax.routingHeader.fromParams({ + name: request.name || '', + }); + return this._innerApiCalls.getGlossary(request, options, callback); + } + batchTranslateText( + request: protosTypes.google.cloud.translation.v3beta1.IBatchTranslateTextRequest, + options?: gax.CallOptions + ): Promise< + [ + LROperation< + protosTypes.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protosTypes.google.cloud.translation.v3beta1.IBatchTranslateMetadata + >, + protosTypes.google.longrunning.IOperation | undefined, + {} | undefined + ] + >; + batchTranslateText( + request: protosTypes.google.cloud.translation.v3beta1.IBatchTranslateTextRequest, + options: gax.CallOptions, + callback: Callback< + LROperation< + protosTypes.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protosTypes.google.cloud.translation.v3beta1.IBatchTranslateMetadata + >, + protosTypes.google.longrunning.IOperation | undefined, + {} | undefined + > + ): void; /** * Translates a large volume of text in asynchronous batch mode. * This function provides real-time output as the inputs are being processed. @@ -618,20 +835,7 @@ class TranslationServiceClient { * Required. Source language code. * @param {string[]} request.targetLanguageCodes * Required. Specify up to 10 language codes here. - * @param {Object[]} 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. - * - * This object should have the same structure as [InputConfig]{@link google.cloud.translation.v3beta1.InputConfig} - * @param {Object} 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. - * - * This object should have the same structure as [OutputConfig]{@link google.cloud.translation.v3beta1.OutputConfig} - * @param {Object.} [request.models] + * @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. @@ -648,10 +852,19 @@ class TranslationServiceClient { * * If the map is empty or a specific model is * not requested for a language pair, then default google model (nmt) is used. - * @param {Object.} [request.glossaries] + * @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 {Object.} [request.labels] + * @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 @@ -660,130 +873,85 @@ class TranslationServiceClient { * 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] - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html} 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 a [gax.Operation]{@link https://googleapis.github.io/gax-nodejs/classes/Operation.html} object. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is a [gax.Operation]{@link https://googleapis.github.io/gax-nodejs/classes/Operation.html} object. + * The first element of the array is an object representing [Operation]{@link google.longrunning.Operation}. * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * const translate = require('@google-cloud/translate'); - * - * const client = new translate.v3beta1.TranslationServiceClient({ - * // optional auth parameters. - * }); - * - * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); - * const sourceLanguageCode = ''; - * const targetLanguageCodes = []; - * const inputConfigs = []; - * const outputConfig = {}; - * const request = { - * parent: formattedParent, - * sourceLanguageCode: sourceLanguageCode, - * targetLanguageCodes: targetLanguageCodes, - * inputConfigs: inputConfigs, - * outputConfig: outputConfig, - * }; - * - * // Handle the operation using the promise pattern. - * client.batchTranslateText(request) - * .then(responses => { - * const [operation, initialApiResponse] = responses; - * - * // Operation#promise starts polling for the completion of the LRO. - * return operation.promise(); - * }) - * .then(responses => { - * const result = responses[0]; - * const metadata = responses[1]; - * const finalApiResponse = responses[2]; - * }) - * .catch(err => { - * console.error(err); - * }); - * - * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); - * const sourceLanguageCode = ''; - * const targetLanguageCodes = []; - * const inputConfigs = []; - * const outputConfig = {}; - * const request = { - * parent: formattedParent, - * sourceLanguageCode: sourceLanguageCode, - * targetLanguageCodes: targetLanguageCodes, - * inputConfigs: inputConfigs, - * outputConfig: outputConfig, - * }; - * - * // Handle the operation using the event emitter pattern. - * client.batchTranslateText(request) - * .then(responses => { - * const [operation, initialApiResponse] = responses; - * - * // Adding a listener for the "complete" event starts polling for the - * // completion of the operation. - * operation.on('complete', (result, metadata, finalApiResponse) => { - * // doSomethingWith(result); - * }); - * - * // Adding a listener for the "progress" event causes the callback to be - * // called on any change in metadata when the operation is polled. - * operation.on('progress', (metadata, apiResponse) => { - * // doSomethingWith(metadata) - * }); - * - * // Adding a listener for the "error" event handles any errors found during polling. - * operation.on('error', err => { - * // throw(err); - * }); - * }) - * .catch(err => { - * console.error(err); - * }); - * - * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); - * const sourceLanguageCode = ''; - * const targetLanguageCodes = []; - * const inputConfigs = []; - * const outputConfig = {}; - * const request = { - * parent: formattedParent, - * sourceLanguageCode: sourceLanguageCode, - * targetLanguageCodes: targetLanguageCodes, - * inputConfigs: inputConfigs, - * outputConfig: outputConfig, - * }; - * - * // Handle the operation using the await pattern. - * const [operation] = await client.batchTranslateText(request); - * - * const [response] = await operation.promise(); */ - batchTranslateText(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; + batchTranslateText( + request: protosTypes.google.cloud.translation.v3beta1.IBatchTranslateTextRequest, + optionsOrCallback?: + | gax.CallOptions + | Callback< + LROperation< + protosTypes.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protosTypes.google.cloud.translation.v3beta1.IBatchTranslateMetadata + >, + protosTypes.google.longrunning.IOperation | undefined, + {} | undefined + >, + callback?: Callback< + LROperation< + protosTypes.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protosTypes.google.cloud.translation.v3beta1.IBatchTranslateMetadata + >, + protosTypes.google.longrunning.IOperation | undefined, + {} | undefined + > + ): Promise< + [ + LROperation< + protosTypes.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protosTypes.google.cloud.translation.v3beta1.IBatchTranslateMetadata + >, + protosTypes.google.longrunning.IOperation | undefined, + {} | undefined + ] + > | void { + request = request || {}; + let options: gax.CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; options = {}; + } else { + options = optionsOrCallback as gax.CallOptions; } - request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers[ 'x-goog-request-params' ] = gax.routingHeader.fromParams({ - parent: request.parent, + parent: request.parent || '', }); - return this._innerApiCalls.batchTranslateText(request, options, callback); } - + createGlossary( + request: protosTypes.google.cloud.translation.v3beta1.ICreateGlossaryRequest, + options?: gax.CallOptions + ): Promise< + [ + LROperation< + protosTypes.google.cloud.translation.v3beta1.IGlossary, + protosTypes.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + >, + protosTypes.google.longrunning.IOperation | undefined, + {} | undefined + ] + >; + createGlossary( + request: protosTypes.google.cloud.translation.v3beta1.ICreateGlossaryRequest, + options: gax.CallOptions, + callback: Callback< + LROperation< + protosTypes.google.cloud.translation.v3beta1.IGlossary, + protosTypes.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + >, + protosTypes.google.longrunning.IOperation | undefined, + {} | undefined + > + ): void; /** * Creates a glossary and returns the long-running operation. Returns * NOT_FOUND, if the project doesn't exist. @@ -792,116 +960,169 @@ class TranslationServiceClient { * The request object that will be sent. * @param {string} request.parent * Required. The project name. - * @param {Object} request.glossary + * @param {google.cloud.translation.v3beta1.Glossary} request.glossary * Required. The glossary to create. - * - * This object should have the same structure as [Glossary]{@link google.cloud.translation.v3beta1.Glossary} - * @param {Object} [options] - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html} 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 a [gax.Operation]{@link https://googleapis.github.io/gax-nodejs/classes/Operation.html} object. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is a [gax.Operation]{@link https://googleapis.github.io/gax-nodejs/classes/Operation.html} object. + * The first element of the array is an object representing [Operation]{@link google.longrunning.Operation}. * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * const translate = require('@google-cloud/translate'); - * - * const client = new translate.v3beta1.TranslationServiceClient({ - * // optional auth parameters. - * }); - * - * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); - * const glossary = {}; - * const request = { - * parent: formattedParent, - * glossary: glossary, - * }; - * - * // Handle the operation using the promise pattern. - * client.createGlossary(request) - * .then(responses => { - * const [operation, initialApiResponse] = responses; - * - * // Operation#promise starts polling for the completion of the LRO. - * return operation.promise(); - * }) - * .then(responses => { - * const result = responses[0]; - * const metadata = responses[1]; - * const finalApiResponse = responses[2]; - * }) - * .catch(err => { - * console.error(err); - * }); - * - * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); - * const glossary = {}; - * const request = { - * parent: formattedParent, - * glossary: glossary, - * }; - * - * // Handle the operation using the event emitter pattern. - * client.createGlossary(request) - * .then(responses => { - * const [operation, initialApiResponse] = responses; - * - * // Adding a listener for the "complete" event starts polling for the - * // completion of the operation. - * operation.on('complete', (result, metadata, finalApiResponse) => { - * // doSomethingWith(result); - * }); - * - * // Adding a listener for the "progress" event causes the callback to be - * // called on any change in metadata when the operation is polled. - * operation.on('progress', (metadata, apiResponse) => { - * // doSomethingWith(metadata) - * }); - * - * // Adding a listener for the "error" event handles any errors found during polling. - * operation.on('error', err => { - * // throw(err); - * }); - * }) - * .catch(err => { - * console.error(err); - * }); - * - * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); - * const glossary = {}; - * const request = { - * parent: formattedParent, - * glossary: glossary, - * }; - * - * // Handle the operation using the await pattern. - * const [operation] = await client.createGlossary(request); - * - * const [response] = await operation.promise(); */ - createGlossary(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; + createGlossary( + request: protosTypes.google.cloud.translation.v3beta1.ICreateGlossaryRequest, + optionsOrCallback?: + | gax.CallOptions + | Callback< + LROperation< + protosTypes.google.cloud.translation.v3beta1.IGlossary, + protosTypes.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + >, + protosTypes.google.longrunning.IOperation | undefined, + {} | undefined + >, + callback?: Callback< + LROperation< + protosTypes.google.cloud.translation.v3beta1.IGlossary, + protosTypes.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + >, + protosTypes.google.longrunning.IOperation | undefined, + {} | undefined + > + ): Promise< + [ + LROperation< + protosTypes.google.cloud.translation.v3beta1.IGlossary, + protosTypes.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + >, + protosTypes.google.longrunning.IOperation | undefined, + {} | undefined + ] + > | void { + request = request || {}; + let options: gax.CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; options = {}; + } else { + options = optionsOrCallback as gax.CallOptions; } - request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers[ 'x-goog-request-params' ] = gax.routingHeader.fromParams({ - parent: request.parent, + parent: request.parent || '', }); - return this._innerApiCalls.createGlossary(request, options, callback); } - + deleteGlossary( + request: protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryRequest, + options?: gax.CallOptions + ): Promise< + [ + LROperation< + protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + >, + protosTypes.google.longrunning.IOperation | undefined, + {} | undefined + ] + >; + deleteGlossary( + request: protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryRequest, + options: gax.CallOptions, + callback: Callback< + LROperation< + protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + >, + protosTypes.google.longrunning.IOperation | undefined, + {} | undefined + > + ): void; + /** + * 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 [Operation]{@link google.longrunning.Operation}. + * The promise has a method named "cancel" which cancels the ongoing API call. + */ + deleteGlossary( + request: protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryRequest, + optionsOrCallback?: + | gax.CallOptions + | Callback< + LROperation< + protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + >, + protosTypes.google.longrunning.IOperation | undefined, + {} | undefined + >, + callback?: Callback< + LROperation< + protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + >, + protosTypes.google.longrunning.IOperation | undefined, + {} | undefined + > + ): Promise< + [ + LROperation< + protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + >, + protosTypes.google.longrunning.IOperation | undefined, + {} | undefined + ] + > | void { + request = request || {}; + 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' + ] = gax.routingHeader.fromParams({ + name: request.name || '', + }); + return this._innerApiCalls.deleteGlossary(request, options, callback); + } + listGlossaries( + request: protosTypes.google.cloud.translation.v3beta1.IListGlossariesRequest, + options?: gax.CallOptions + ): Promise< + [ + protosTypes.google.cloud.translation.v3beta1.IGlossary[], + protosTypes.google.cloud.translation.v3beta1.IListGlossariesRequest | null, + protosTypes.google.cloud.translation.v3beta1.IListGlossariesResponse + ] + >; + listGlossaries( + request: protosTypes.google.cloud.translation.v3beta1.IListGlossariesRequest, + options: gax.CallOptions, + callback: Callback< + protosTypes.google.cloud.translation.v3beta1.IGlossary[], + protosTypes.google.cloud.translation.v3beta1.IListGlossariesRequest | null, + protosTypes.google.cloud.translation.v3beta1.IListGlossariesResponse + > + ): void; /** * Lists glossaries in a project. Returns NOT_FOUND, if the project doesn't * exist. @@ -911,101 +1132,67 @@ class TranslationServiceClient { * @param {string} request.parent * Required. The name of the project from which to list all of the glossaries. * @param {number} [request.pageSize] - * The maximum number of resources contained in the underlying API - * response. If page streaming is performed per-resource, this - * parameter does not affect the return value. If page streaming is - * performed per-page, this determines the maximum number of - * resources in a page. + * 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] - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html} for the details. - * @param {function(?Error, ?Array, ?Object, ?Object)} [callback] - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is Array of [Glossary]{@link google.cloud.translation.v3beta1.Glossary}. - * - * When autoPaginate: false is specified through options, it contains the result - * in a single response. If the response indicates the next page exists, the third - * parameter is set to be used for the next request object. The fourth parameter keeps - * the raw response object of an object representing [ListGlossariesResponse]{@link google.cloud.translation.v3beta1.ListGlossariesResponse}. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/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 [Glossary]{@link google.cloud.translation.v3beta1.Glossary}. + * The first element of the array is an object representing [ListGlossariesResponse]{@link google.cloud.translation.v3beta1.ListGlossariesResponse}. * * When autoPaginate: false is specified through options, the array has three elements. - * The first element is Array of [Glossary]{@link google.cloud.translation.v3beta1.Glossary} in a single response. + * The first element is Array of [ListGlossariesResponse]{@link google.cloud.translation.v3beta1.ListGlossariesResponse} in a single response. * The second element is the next request object if the response * indicates the next page exists, or null. The third element is * an object representing [ListGlossariesResponse]{@link google.cloud.translation.v3beta1.ListGlossariesResponse}. * * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * const translate = require('@google-cloud/translate'); - * - * const client = new translate.v3beta1.TranslationServiceClient({ - * // optional auth parameters. - * }); - * - * // Iterate over all elements. - * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); - * - * client.listGlossaries({parent: formattedParent}) - * .then(responses => { - * const resources = responses[0]; - * for (const resource of resources) { - * // doThingsWith(resource) - * } - * }) - * .catch(err => { - * console.error(err); - * }); - * - * // Or obtain the paged response. - * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); - * - * - * const options = {autoPaginate: false}; - * const callback = responses => { - * // The actual resources in a response. - * const resources = responses[0]; - * // The next request if the response shows that there are more responses. - * const nextRequest = responses[1]; - * // The actual response object, if necessary. - * // const rawResponse = responses[2]; - * for (const resource of resources) { - * // doThingsWith(resource); - * } - * if (nextRequest) { - * // Fetch the next page. - * return client.listGlossaries(nextRequest, options).then(callback); - * } - * } - * client.listGlossaries({parent: formattedParent}, options) - * .then(callback) - * .catch(err => { - * console.error(err); - * }); */ - listGlossaries(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; + listGlossaries( + request: protosTypes.google.cloud.translation.v3beta1.IListGlossariesRequest, + optionsOrCallback?: + | gax.CallOptions + | Callback< + protosTypes.google.cloud.translation.v3beta1.IGlossary[], + protosTypes.google.cloud.translation.v3beta1.IListGlossariesRequest | null, + protosTypes.google.cloud.translation.v3beta1.IListGlossariesResponse + >, + callback?: Callback< + protosTypes.google.cloud.translation.v3beta1.IGlossary[], + protosTypes.google.cloud.translation.v3beta1.IListGlossariesRequest | null, + protosTypes.google.cloud.translation.v3beta1.IListGlossariesResponse + > + ): Promise< + [ + protosTypes.google.cloud.translation.v3beta1.IGlossary[], + protosTypes.google.cloud.translation.v3beta1.IListGlossariesRequest | null, + protosTypes.google.cloud.translation.v3beta1.IListGlossariesResponse + ] + > | void { + request = request || {}; + let options: gax.CallOptions; + if (typeof optionsOrCallback === 'function' && callback === undefined) { + callback = optionsOrCallback; options = {}; + } else { + options = optionsOrCallback as gax.CallOptions; } - request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers[ 'x-goog-request-params' ] = gax.routingHeader.fromParams({ - parent: request.parent, + parent: request.parent || '', }); - return this._innerApiCalls.listGlossaries(request, options, callback); } @@ -1027,293 +1214,138 @@ class TranslationServiceClient { * @param {string} request.parent * Required. The name of the project from which to list all of the glossaries. * @param {number} [request.pageSize] - * The maximum number of resources contained in the underlying API - * response. If page streaming is performed per-resource, this - * parameter does not affect the return value. If page streaming is - * performed per-page, this determines the maximum number of - * resources in a page. + * 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] - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html} for the 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 [Glossary]{@link google.cloud.translation.v3beta1.Glossary} on 'data' event. - * - * @example - * - * const translate = require('@google-cloud/translate'); - * - * const client = new translate.v3beta1.TranslationServiceClient({ - * // optional auth parameters. - * }); - * - * const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); - * client.listGlossariesStream({parent: formattedParent}) - * .on('data', element => { - * // doThingsWith(element) - * }).on('error', err => { - * console.log(err); - * }); */ - listGlossariesStream(request, options) { - options = options || {}; - + listGlossariesStream( + request?: protosTypes.google.cloud.translation.v3beta1.IListGlossariesRequest, + options?: gax.CallOptions | {} + ): Transform { + request = request || {}; + const callSettings = new gax.CallSettings(options); return this._descriptors.page.listGlossaries.createStream( - this._innerApiCalls.listGlossaries, + this._innerApiCalls.listGlossaries as gax.GaxCall, request, - options + callSettings ); } + // -------------------- + // -- Path templates -- + // -------------------- /** - * 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] - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html} 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 [Glossary]{@link google.cloud.translation.v3beta1.Glossary}. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [Glossary]{@link google.cloud.translation.v3beta1.Glossary}. - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * const translate = require('@google-cloud/translate'); - * - * const client = new translate.v3beta1.TranslationServiceClient({ - * // optional auth parameters. - * }); + * Return a fully-qualified location resource name string. * - * const formattedName = client.glossaryPath('[PROJECT]', '[LOCATION]', '[GLOSSARY]'); - * client.getGlossary({name: formattedName}) - * .then(responses => { - * const response = responses[0]; - * // doThingsWith(response) - * }) - * .catch(err => { - * console.error(err); - * }); + * @param {string} project + * @param {string} location + * @returns {string} Resource name string. */ - getGlossary(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - request = request || {}; - options = options || {}; - options.otherArgs = options.otherArgs || {}; - options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = gax.routingHeader.fromParams({ - name: request.name, + locationPath(project: string, location: string) { + return this._pathTemplates.locationPathTemplate.render({ + project, + location, }); - - return this._innerApiCalls.getGlossary(request, options, callback); } /** - * Deletes a glossary, or cancels glossary construction - * if the glossary isn't created yet. - * Returns NOT_FOUND, if the glossary doesn't exist. + * Parse the project from Location resource. * - * @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] - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/interfaces/CallOptions.html} 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 a [gax.Operation]{@link https://googleapis.github.io/gax-nodejs/classes/Operation.html} object. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is a [gax.Operation]{@link https://googleapis.github.io/gax-nodejs/classes/Operation.html} object. - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * const translate = require('@google-cloud/translate'); - * - * const client = new translate.v3beta1.TranslationServiceClient({ - * // optional auth parameters. - * }); - * - * const formattedName = client.glossaryPath('[PROJECT]', '[LOCATION]', '[GLOSSARY]'); - * - * // Handle the operation using the promise pattern. - * client.deleteGlossary({name: formattedName}) - * .then(responses => { - * const [operation, initialApiResponse] = responses; - * - * // Operation#promise starts polling for the completion of the LRO. - * return operation.promise(); - * }) - * .then(responses => { - * const result = responses[0]; - * const metadata = responses[1]; - * const finalApiResponse = responses[2]; - * }) - * .catch(err => { - * console.error(err); - * }); - * - * const formattedName = client.glossaryPath('[PROJECT]', '[LOCATION]', '[GLOSSARY]'); - * - * // Handle the operation using the event emitter pattern. - * client.deleteGlossary({name: formattedName}) - * .then(responses => { - * const [operation, initialApiResponse] = responses; - * - * // Adding a listener for the "complete" event starts polling for the - * // completion of the operation. - * operation.on('complete', (result, metadata, finalApiResponse) => { - * // doSomethingWith(result); - * }); - * - * // Adding a listener for the "progress" event causes the callback to be - * // called on any change in metadata when the operation is polled. - * operation.on('progress', (metadata, apiResponse) => { - * // doSomethingWith(metadata) - * }); - * - * // Adding a listener for the "error" event handles any errors found during polling. - * operation.on('error', err => { - * // throw(err); - * }); - * }) - * .catch(err => { - * console.error(err); - * }); - * - * const formattedName = client.glossaryPath('[PROJECT]', '[LOCATION]', '[GLOSSARY]'); - * - * // Handle the operation using the await pattern. - * const [operation] = await client.deleteGlossary({name: formattedName}); - * - * const [response] = await operation.promise(); + * @param {string} locationName + * A fully-qualified path representing Location resource. + * @returns {string} A string representing the project. */ - deleteGlossary(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - request = request || {}; - options = options || {}; - options.otherArgs = options.otherArgs || {}; - options.otherArgs.headers = options.otherArgs.headers || {}; - options.otherArgs.headers[ - 'x-goog-request-params' - ] = gax.routingHeader.fromParams({ - name: request.name, - }); - - return this._innerApiCalls.deleteGlossary(request, options, callback); + matchProjectFromLocationName(locationName: string) { + return this._pathTemplates.locationPathTemplate.match(locationName).project; } - // -------------------- - // -- Path templates -- - // -------------------- - /** - * Return a fully-qualified glossary resource name string. + * Parse the location from Location resource. * - * @param {String} project - * @param {String} location - * @param {String} glossary - * @returns {String} + * @param {string} locationName + * A fully-qualified path representing Location resource. + * @returns {string} A string representing the location. */ - glossaryPath(project, location, glossary) { - return this._pathTemplates.glossaryPathTemplate.render({ - project: project, - location: location, - glossary: glossary, - }); + matchLocationFromLocationName(locationName: string) { + return this._pathTemplates.locationPathTemplate.match(locationName) + .location; } /** - * Return a fully-qualified location resource name string. + * Return a fully-qualified glossary resource name string. * - * @param {String} project - * @param {String} location - * @returns {String} + * @param {string} project + * @param {string} location + * @param {string} glossary + * @returns {string} Resource name string. */ - locationPath(project, location) { - return this._pathTemplates.locationPathTemplate.render({ - project: project, - location: location, + glossaryPath(project: string, location: string, glossary: string) { + return this._pathTemplates.glossaryPathTemplate.render({ + project, + location, + glossary, }); } /** - * Parse the glossaryName from a glossary resource. + * Parse the project from Glossary resource. * - * @param {String} glossaryName - * A fully-qualified path representing a glossary resources. - * @returns {String} - A string representing the project. + * @param {string} glossaryName + * A fully-qualified path representing Glossary resource. + * @returns {string} A string representing the project. */ - matchProjectFromGlossaryName(glossaryName) { + matchProjectFromGlossaryName(glossaryName: string) { return this._pathTemplates.glossaryPathTemplate.match(glossaryName).project; } /** - * Parse the glossaryName from a glossary resource. + * Parse the location from Glossary resource. * - * @param {String} glossaryName - * A fully-qualified path representing a glossary resources. - * @returns {String} - A string representing the location. + * @param {string} glossaryName + * A fully-qualified path representing Glossary resource. + * @returns {string} A string representing the location. */ - matchLocationFromGlossaryName(glossaryName) { + matchLocationFromGlossaryName(glossaryName: string) { return this._pathTemplates.glossaryPathTemplate.match(glossaryName) .location; } /** - * Parse the glossaryName from a glossary resource. + * Parse the glossary from Glossary resource. * - * @param {String} glossaryName - * A fully-qualified path representing a glossary resources. - * @returns {String} - A string representing the glossary. + * @param {string} glossaryName + * A fully-qualified path representing Glossary resource. + * @returns {string} A string representing the glossary. */ - matchGlossaryFromGlossaryName(glossaryName) { + matchGlossaryFromGlossaryName(glossaryName: string) { return this._pathTemplates.glossaryPathTemplate.match(glossaryName) .glossary; } /** - * Parse the locationName from a location resource. - * - * @param {String} locationName - * A fully-qualified path representing a location resources. - * @returns {String} - A string representing the project. - */ - matchProjectFromLocationName(locationName) { - return this._pathTemplates.locationPathTemplate.match(locationName).project; - } - - /** - * Parse the locationName from a location resource. + * Terminate the GRPC channel and close the client. * - * @param {String} locationName - * A fully-qualified path representing a location resources. - * @returns {String} - A string representing the location. + * The client will no longer be usable and all future behavior is undefined. */ - matchLocationFromLocationName(locationName) { - return this._pathTemplates.locationPathTemplate.match(locationName) - .location; + close(): Promise { + if (!this._terminated) { + return this._translationServiceStub.then(stub => { + this._terminated = true; + stub.close(); + }); + } + return Promise.resolve(); } } - -module.exports = TranslationServiceClient; diff --git a/src/v3beta1/translation_service_client_config.json b/src/v3beta1/translation_service_client_config.json index 21537ac3..db6fab77 100644 --- a/src/v3beta1/translation_service_client_config.json +++ b/src/v3beta1/translation_service_client_config.json @@ -2,11 +2,11 @@ "interfaces": { "google.cloud.translation.v3beta1.TranslationService": { "retry_codes": { + "non_idempotent": [], "idempotent": [ "DEADLINE_EXCEEDED", "UNAVAILABLE" - ], - "non_idempotent": [] + ] }, "retry_params": { "default": { @@ -14,50 +14,50 @@ "retry_delay_multiplier": 1.3, "max_retry_delay_millis": 60000, "initial_rpc_timeout_millis": 20000, - "rpc_timeout_multiplier": 1.0, + "rpc_timeout_multiplier": 1, "max_rpc_timeout_millis": 20000, "total_timeout_millis": 600000 } }, "methods": { "TranslateText": { - "timeout_millis": 60000, + "timeout_millis": 600000, "retry_codes_name": "non_idempotent", "retry_params_name": "default" }, "DetectLanguage": { - "timeout_millis": 60000, + "timeout_millis": 600000, "retry_codes_name": "non_idempotent", "retry_params_name": "default" }, "GetSupportedLanguages": { - "timeout_millis": 60000, + "timeout_millis": 600000, "retry_codes_name": "idempotent", "retry_params_name": "default" }, "BatchTranslateText": { - "timeout_millis": 60000, + "timeout_millis": 600000, "retry_codes_name": "non_idempotent", "retry_params_name": "default" }, "CreateGlossary": { - "timeout_millis": 60000, + "timeout_millis": 600000, "retry_codes_name": "non_idempotent", "retry_params_name": "default" }, "ListGlossaries": { - "timeout_millis": 60000, + "timeout_millis": 600000, "retry_codes_name": "idempotent", "retry_params_name": "default" }, "GetGlossary": { - "timeout_millis": 60000, + "timeout_millis": 600000, "retry_codes_name": "idempotent", "retry_params_name": "default" }, "DeleteGlossary": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", + "timeout_millis": 600000, + "retry_codes_name": "idempotent", "retry_params_name": "default" } } diff --git a/synth.metadata b/synth.metadata index 6d535140..3a1dd350 100644 --- a/synth.metadata +++ b/synth.metadata @@ -1,12 +1,12 @@ { - "updateTime": "2019-11-20T20:59:24.452560Z", + "updateTime": "2019-11-21T07:10:28.256353Z", "sources": [ { "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "16543773103e2619d2b5f52456264de5bb9be104", - "internalRef": "281423227" + "sha": "5bc0fecee454f857cec042fb99fe2d22e1bff5bc", + "internalRef": "281635572" } }, { @@ -18,6 +18,15 @@ } ], "destinations": [ + { + "client": { + "source": "googleapis", + "apiName": "translate", + "apiVersion": "v3beta1", + "language": "typescript", + "generator": "gapic-generator-typescript" + } + }, { "client": { "source": "googleapis", diff --git a/synth.py b/synth.py index 9fef1c0f..8d6160bc 100644 --- a/synth.py +++ b/synth.py @@ -21,29 +21,19 @@ # Run the gapic generator gapic = gcp.GAPICMicrogenerator() -versions = ['v3'] +versions = ['v3beta1', 'v3'] +name = 'translate' for version in versions: library = gapic.typescript_library( - 'translate', + name, + proto_path=f"google/cloud/{name}/{version}", generator_args={ - "grpc-service-config": "google/cloud/translate/v3/translate_grpc_service_config.json", - "package-name":"@google-cloud/translate" + "grpc-service-config": f"google/cloud/{name}/{version}/{name}_grpc_service_config.json", + "package-name": f"@google-cloud/{name}" }, + extra_proto_files=['google/cloud/common_resources.proto'], version=version) -s.copy(library, excludes=['README.md', 'package.json', 'src/index.ts']) - -# Update path discovery due to build/ dir and TypeScript conversion. -s.replace("test/gapic-*.js", "../../package.json", "../../../package.json") - -# [START fix-dead-link] -s.replace('**/doc/google/protobuf/doc_timestamp.js', - 'https:\/\/cloud\.google\.com[\s\*]*http:\/\/(.*)[\s\*]*\)', - r"https://\1)") - -s.replace('**/doc/google/protobuf/doc_timestamp.js', - 'toISOString\]', - 'toISOString)') -# [END fix-dead-link] + s.copy(library, excludes=['README.md', 'package.json', 'src/index.ts']) logging.basicConfig(level=logging.DEBUG) common_templates = gcp.CommonTemplates() @@ -53,3 +43,4 @@ # Node.js specific cleanup subprocess.run(["npm", "install"]) subprocess.run(["npm", "run", "fix"]) +subprocess.run(["npx", "compileProtos", "src"]) diff --git a/system-test/.eslintrc.yml b/system-test/.eslintrc.yml index f9605165..dc5d9b01 100644 --- a/system-test/.eslintrc.yml +++ b/system-test/.eslintrc.yml @@ -1,5 +1,4 @@ --- env: mocha: true -rules: - no-console: off + diff --git a/system-test/fixtures/sample/src/index.js b/system-test/fixtures/sample/src/index.js index 3c0ba06f..4a53d1c4 100644 --- a/system-test/fixtures/sample/src/index.js +++ b/system-test/fixtures/sample/src/index.js @@ -21,7 +21,6 @@ const translation = require('@google-cloud/translate'); function main() { const translationServiceClient = new translation.TranslationServiceClient(); - console.log('translationServiceClient was created!'); } main(); diff --git a/system-test/fixtures/sample/src/index.ts b/system-test/fixtures/sample/src/index.ts index 96dcfd2b..299f64d2 100644 --- a/system-test/fixtures/sample/src/index.ts +++ b/system-test/fixtures/sample/src/index.ts @@ -20,7 +20,6 @@ import {TranslationServiceClient} from '@google-cloud/translate'; function main() { const translationServiceClient = new TranslationServiceClient(); - console.log("translationServiceClient was created!"); } main(); diff --git a/test/gapic-translation_service-v3beta1.ts b/test/gapic-translation_service-v3beta1.ts new file mode 100644 index 00000000..5aed0f07 --- /dev/null +++ b/test/gapic-translation_service-v3beta1.ts @@ -0,0 +1,565 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// ** This file is automatically generated by gapic-generator-typescript. ** +// ** https://github.com/googleapis/gapic-generator-typescript ** +// ** All changes to this file may be overwritten. ** + +import * as protosTypes from '../protos/protos'; +import * as assert from 'assert'; +const translationserviceModule = require('../src'); + +const FAKE_STATUS_CODE = 1; +class FakeError { + name: string; + message: string; + code: number; + constructor(n: number) { + this.name = 'fakeName'; + this.message = 'fake message'; + this.code = n; + } +} +const error = new FakeError(FAKE_STATUS_CODE); +export interface Callback { + (err: FakeError | null, response?: {} | null): void; +} + +export class Operation { + constructor() {} + promise() {} +} + +function mockSimpleGrpcMethod( + expectedRequest: {}, + response: {} | null, + error: FakeError | null +) { + return (actualRequest: {}, options: {}, callback: Callback) => { + assert.deepStrictEqual(actualRequest, expectedRequest); + if (error) { + callback(error); + } else if (response) { + callback(null, response); + } else { + callback(null); + } + }; +} +function mockLongRunningGrpcMethod( + expectedRequest: {}, + response: {} | null, + error?: {} | null +) { + return (request: {}) => { + assert.deepStrictEqual(request, expectedRequest); + const mockOperation = { + promise() { + return new Promise((resolve, reject) => { + if (error) { + reject(error); + } else { + resolve([response]); + } + }); + }, + }; + return Promise.resolve([mockOperation]); + }; +} +describe('TranslationServiceClient', () => { + it('has servicePath', () => { + const servicePath = + translationserviceModule.v3beta1.TranslationServiceClient.servicePath; + assert(servicePath); + }); + it('has apiEndpoint', () => { + const apiEndpoint = + translationserviceModule.v3beta1.TranslationServiceClient.apiEndpoint; + assert(apiEndpoint); + }); + it('has port', () => { + const port = translationserviceModule.v3beta1.TranslationServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); + it('should create a client with no option', () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient(); + assert(client); + }); + it('should create a client with gRPC option', () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + fallback: true, + } + ); + assert(client); + }); + describe('translateText', () => { + it('invokes translateText without error', done => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + // Mock request + const request: protosTypes.google.cloud.translation.v3beta1.ITranslateTextRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock gRPC layer + client._innerApiCalls.translateText = mockSimpleGrpcMethod( + request, + expectedResponse, + null + ); + client.translateText(request, (err: {}, response: {}) => { + assert.ifError(err); + assert.deepStrictEqual(response, expectedResponse); + done(); + }); + }); + + it('invokes translateText with error', done => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + // Mock request + const request: protosTypes.google.cloud.translation.v3beta1.ITranslateTextRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock gRPC layer + client._innerApiCalls.translateText = mockSimpleGrpcMethod( + request, + null, + error + ); + client.translateText(request, (err: FakeError, response: {}) => { + assert(err instanceof FakeError); + assert.strictEqual(err.code, FAKE_STATUS_CODE); + assert(typeof response === 'undefined'); + done(); + }); + }); + }); + describe('detectLanguage', () => { + it('invokes detectLanguage without error', done => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + // Mock request + const request: protosTypes.google.cloud.translation.v3beta1.IDetectLanguageRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock gRPC layer + client._innerApiCalls.detectLanguage = mockSimpleGrpcMethod( + request, + expectedResponse, + null + ); + client.detectLanguage(request, (err: {}, response: {}) => { + assert.ifError(err); + assert.deepStrictEqual(response, expectedResponse); + done(); + }); + }); + + it('invokes detectLanguage with error', done => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + // Mock request + const request: protosTypes.google.cloud.translation.v3beta1.IDetectLanguageRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock gRPC layer + client._innerApiCalls.detectLanguage = mockSimpleGrpcMethod( + request, + null, + error + ); + client.detectLanguage(request, (err: FakeError, response: {}) => { + assert(err instanceof FakeError); + assert.strictEqual(err.code, FAKE_STATUS_CODE); + assert(typeof response === 'undefined'); + done(); + }); + }); + }); + describe('getSupportedLanguages', () => { + it('invokes getSupportedLanguages without error', done => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + // Mock request + const request: protosTypes.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock gRPC layer + client._innerApiCalls.getSupportedLanguages = mockSimpleGrpcMethod( + request, + expectedResponse, + null + ); + client.getSupportedLanguages(request, (err: {}, response: {}) => { + assert.ifError(err); + assert.deepStrictEqual(response, expectedResponse); + done(); + }); + }); + + it('invokes getSupportedLanguages with error', done => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + // Mock request + const request: protosTypes.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock gRPC layer + client._innerApiCalls.getSupportedLanguages = mockSimpleGrpcMethod( + request, + null, + error + ); + client.getSupportedLanguages(request, (err: FakeError, response: {}) => { + assert(err instanceof FakeError); + assert.strictEqual(err.code, FAKE_STATUS_CODE); + assert(typeof response === 'undefined'); + done(); + }); + }); + }); + describe('getGlossary', () => { + it('invokes getGlossary without error', done => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + // Mock request + const request: protosTypes.google.cloud.translation.v3beta1.IGetGlossaryRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock gRPC layer + client._innerApiCalls.getGlossary = mockSimpleGrpcMethod( + request, + expectedResponse, + null + ); + client.getGlossary(request, (err: {}, response: {}) => { + assert.ifError(err); + assert.deepStrictEqual(response, expectedResponse); + done(); + }); + }); + + it('invokes getGlossary with error', done => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + // Mock request + const request: protosTypes.google.cloud.translation.v3beta1.IGetGlossaryRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock gRPC layer + client._innerApiCalls.getGlossary = mockSimpleGrpcMethod( + request, + null, + error + ); + client.getGlossary(request, (err: FakeError, response: {}) => { + assert(err instanceof FakeError); + assert.strictEqual(err.code, FAKE_STATUS_CODE); + assert(typeof response === 'undefined'); + done(); + }); + }); + }); + describe('batchTranslateText', () => { + it('invokes batchTranslateText without error', done => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + // Mock request + const request: protosTypes.google.cloud.translation.v3beta1.IBatchTranslateTextRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock gRPC layer + client._innerApiCalls.batchTranslateText = mockLongRunningGrpcMethod( + request, + expectedResponse + ); + client + .batchTranslateText(request) + .then((responses: [Operation]) => { + const operation = responses[0]; + return operation ? operation.promise() : {}; + }) + .then((responses: [Operation]) => { + assert.deepStrictEqual(responses[0], expectedResponse); + done(); + }) + .catch((err: {}) => { + done(err); + }); + }); + + it('invokes batchTranslateText with error', done => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + // Mock request + const request: protosTypes.google.cloud.translation.v3beta1.IBatchTranslateTextRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock gRPC layer + client._innerApiCalls.batchTranslateText = mockLongRunningGrpcMethod( + request, + null, + error + ); + client + .batchTranslateText(request) + .then((responses: [Operation]) => { + const operation = responses[0]; + return operation ? operation.promise() : {}; + }) + .then(() => { + assert.fail(); + }) + .catch((err: FakeError) => { + assert(err instanceof FakeError); + assert.strictEqual(err.code, FAKE_STATUS_CODE); + done(); + }); + }); + }); + describe('createGlossary', () => { + it('invokes createGlossary without error', done => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + // Mock request + const request: protosTypes.google.cloud.translation.v3beta1.ICreateGlossaryRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock gRPC layer + client._innerApiCalls.createGlossary = mockLongRunningGrpcMethod( + request, + expectedResponse + ); + client + .createGlossary(request) + .then((responses: [Operation]) => { + const operation = responses[0]; + return operation ? operation.promise() : {}; + }) + .then((responses: [Operation]) => { + assert.deepStrictEqual(responses[0], expectedResponse); + done(); + }) + .catch((err: {}) => { + done(err); + }); + }); + + it('invokes createGlossary with error', done => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + // Mock request + const request: protosTypes.google.cloud.translation.v3beta1.ICreateGlossaryRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock gRPC layer + client._innerApiCalls.createGlossary = mockLongRunningGrpcMethod( + request, + null, + error + ); + client + .createGlossary(request) + .then((responses: [Operation]) => { + const operation = responses[0]; + return operation ? operation.promise() : {}; + }) + .then(() => { + assert.fail(); + }) + .catch((err: FakeError) => { + assert(err instanceof FakeError); + assert.strictEqual(err.code, FAKE_STATUS_CODE); + done(); + }); + }); + }); + describe('deleteGlossary', () => { + it('invokes deleteGlossary without error', done => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + // Mock request + const request: protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock gRPC layer + client._innerApiCalls.deleteGlossary = mockLongRunningGrpcMethod( + request, + expectedResponse + ); + client + .deleteGlossary(request) + .then((responses: [Operation]) => { + const operation = responses[0]; + return operation ? operation.promise() : {}; + }) + .then((responses: [Operation]) => { + assert.deepStrictEqual(responses[0], expectedResponse); + done(); + }) + .catch((err: {}) => { + done(err); + }); + }); + + it('invokes deleteGlossary with error', done => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + // Mock request + const request: protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock gRPC layer + client._innerApiCalls.deleteGlossary = mockLongRunningGrpcMethod( + request, + null, + error + ); + client + .deleteGlossary(request) + .then((responses: [Operation]) => { + const operation = responses[0]; + return operation ? operation.promise() : {}; + }) + .then(() => { + assert.fail(); + }) + .catch((err: FakeError) => { + assert(err instanceof FakeError); + assert.strictEqual(err.code, FAKE_STATUS_CODE); + done(); + }); + }); + }); + describe('listGlossaries', () => { + it('invokes listGlossaries without error', done => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + // Mock request + const request: protosTypes.google.cloud.translation.v3beta1.IListGlossariesRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock Grpc layer + client._innerApiCalls.listGlossaries = ( + actualRequest: {}, + options: {}, + callback: Callback + ) => { + assert.deepStrictEqual(actualRequest, request); + callback(null, expectedResponse); + }; + client.listGlossaries(request, (err: FakeError, response: {}) => { + assert.ifError(err); + assert.deepStrictEqual(response, expectedResponse); + done(); + }); + }); + }); + describe('listGlossariesStream', () => { + it('invokes listGlossariesStream without error', done => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + // Mock request + const request: protosTypes.google.cloud.translation.v3beta1.IListGlossariesRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock Grpc layer + client._innerApiCalls.listGlossaries = ( + actualRequest: {}, + options: {}, + callback: Callback + ) => { + assert.deepStrictEqual(actualRequest, request); + callback(null, expectedResponse); + }; + const stream = client + .listGlossariesStream(request, {}) + .on('data', (response: {}) => { + assert.deepStrictEqual(response, expectedResponse); + done(); + }) + .on('error', (err: FakeError) => { + done(err); + }); + stream.write(request); + }); + }); +}); diff --git a/test/gapic-v3beta1.js b/test/gapic-v3beta1.js deleted file mode 100644 index 22251b78..00000000 --- a/test/gapic-v3beta1.js +++ /dev/null @@ -1,709 +0,0 @@ -// Copyright 2019 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -'use strict'; - -const assert = require('assert'); - -const translateModule = require('../src'); - -const FAKE_STATUS_CODE = 1; -const error = new Error(); -error.code = FAKE_STATUS_CODE; - -describe('TranslationServiceClient', () => { - it('has servicePath', () => { - const servicePath = - translateModule.v3beta1.TranslationServiceClient.servicePath; - assert(servicePath); - }); - - it('has apiEndpoint', () => { - const apiEndpoint = - translateModule.v3beta1.TranslationServiceClient.apiEndpoint; - assert(apiEndpoint); - }); - - it('has port', () => { - const port = translateModule.v3beta1.TranslationServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - - it('should create a client with no options', () => { - const client = new translateModule.v3beta1.TranslationServiceClient(); - assert(client); - }); - - it('should create a client with gRPC fallback', () => { - const client = new translateModule.v3beta1.TranslationServiceClient({ - fallback: true, - }); - assert(client); - }); - - describe('translateText', () => { - it('invokes translateText without error', done => { - const client = new translateModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - - // Mock request - const contents = []; - const targetLanguageCode = 'targetLanguageCode1323228230'; - const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); - const request = { - contents: contents, - targetLanguageCode: targetLanguageCode, - parent: formattedParent, - }; - - // Mock response - const expectedResponse = {}; - - // Mock Grpc layer - client._innerApiCalls.translateText = mockSimpleGrpcMethod( - request, - expectedResponse - ); - - client.translateText(request, (err, response) => { - assert.ifError(err); - assert.deepStrictEqual(response, expectedResponse); - done(); - }); - }); - - it('invokes translateText with error', done => { - const client = new translateModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - - // Mock request - const contents = []; - const targetLanguageCode = 'targetLanguageCode1323228230'; - const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); - const request = { - contents: contents, - targetLanguageCode: targetLanguageCode, - parent: formattedParent, - }; - - // Mock Grpc layer - client._innerApiCalls.translateText = mockSimpleGrpcMethod( - request, - null, - error - ); - - client.translateText(request, (err, response) => { - assert(err instanceof Error); - assert.strictEqual(err.code, FAKE_STATUS_CODE); - assert(typeof response === 'undefined'); - done(); - }); - }); - }); - - describe('detectLanguage', () => { - it('invokes detectLanguage without error', done => { - const client = new translateModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - - // Mock request - const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); - const request = { - parent: formattedParent, - }; - - // Mock response - const expectedResponse = {}; - - // Mock Grpc layer - client._innerApiCalls.detectLanguage = mockSimpleGrpcMethod( - request, - expectedResponse - ); - - client.detectLanguage(request, (err, response) => { - assert.ifError(err); - assert.deepStrictEqual(response, expectedResponse); - done(); - }); - }); - - it('invokes detectLanguage with error', done => { - const client = new translateModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - - // Mock request - const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); - const request = { - parent: formattedParent, - }; - - // Mock Grpc layer - client._innerApiCalls.detectLanguage = mockSimpleGrpcMethod( - request, - null, - error - ); - - client.detectLanguage(request, (err, response) => { - assert(err instanceof Error); - assert.strictEqual(err.code, FAKE_STATUS_CODE); - assert(typeof response === 'undefined'); - done(); - }); - }); - }); - - describe('getSupportedLanguages', () => { - it('invokes getSupportedLanguages without error', done => { - const client = new translateModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - - // Mock request - const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); - const request = { - parent: formattedParent, - }; - - // Mock response - const expectedResponse = {}; - - // Mock Grpc layer - client._innerApiCalls.getSupportedLanguages = mockSimpleGrpcMethod( - request, - expectedResponse - ); - - client.getSupportedLanguages(request, (err, response) => { - assert.ifError(err); - assert.deepStrictEqual(response, expectedResponse); - done(); - }); - }); - - it('invokes getSupportedLanguages with error', done => { - const client = new translateModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - - // Mock request - const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); - const request = { - parent: formattedParent, - }; - - // Mock Grpc layer - client._innerApiCalls.getSupportedLanguages = mockSimpleGrpcMethod( - request, - null, - error - ); - - client.getSupportedLanguages(request, (err, response) => { - assert(err instanceof Error); - assert.strictEqual(err.code, FAKE_STATUS_CODE); - assert(typeof response === 'undefined'); - done(); - }); - }); - }); - - describe('batchTranslateText', function() { - it('invokes batchTranslateText without error', done => { - const client = new translateModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - - // Mock request - const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); - const sourceLanguageCode = 'sourceLanguageCode1687263568'; - const targetLanguageCodes = []; - const inputConfigs = []; - const outputConfig = {}; - const request = { - parent: formattedParent, - sourceLanguageCode: sourceLanguageCode, - targetLanguageCodes: targetLanguageCodes, - inputConfigs: inputConfigs, - outputConfig: outputConfig, - }; - - // Mock response - const totalCharacters = 1368640955; - const translatedCharacters = 1337326221; - const failedCharacters = 1723028396; - const expectedResponse = { - totalCharacters: totalCharacters, - translatedCharacters: translatedCharacters, - failedCharacters: failedCharacters, - }; - - // Mock Grpc layer - client._innerApiCalls.batchTranslateText = mockLongRunningGrpcMethod( - request, - expectedResponse - ); - - client - .batchTranslateText(request) - .then(responses => { - const operation = responses[0]; - return operation.promise(); - }) - .then(responses => { - assert.deepStrictEqual(responses[0], expectedResponse); - done(); - }) - .catch(err => { - done(err); - }); - }); - - it('invokes batchTranslateText with error', done => { - const client = new translateModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - - // Mock request - const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); - const sourceLanguageCode = 'sourceLanguageCode1687263568'; - const targetLanguageCodes = []; - const inputConfigs = []; - const outputConfig = {}; - const request = { - parent: formattedParent, - sourceLanguageCode: sourceLanguageCode, - targetLanguageCodes: targetLanguageCodes, - inputConfigs: inputConfigs, - outputConfig: outputConfig, - }; - - // Mock Grpc layer - client._innerApiCalls.batchTranslateText = mockLongRunningGrpcMethod( - request, - null, - error - ); - - client - .batchTranslateText(request) - .then(responses => { - const operation = responses[0]; - return operation.promise(); - }) - .then(() => { - assert.fail(); - }) - .catch(err => { - assert(err instanceof Error); - assert.strictEqual(err.code, FAKE_STATUS_CODE); - done(); - }); - }); - - it('has longrunning decoder functions', () => { - const client = new translateModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert( - client._descriptors.longrunning.batchTranslateText - .responseDecoder instanceof Function - ); - assert( - client._descriptors.longrunning.batchTranslateText - .metadataDecoder instanceof Function - ); - }); - }); - - describe('createGlossary', function() { - it('invokes createGlossary without error', done => { - const client = new translateModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - - // Mock request - const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); - const glossary = {}; - const request = { - parent: formattedParent, - glossary: glossary, - }; - - // Mock response - const name = 'name3373707'; - const entryCount = 811131134; - const expectedResponse = { - name: name, - entryCount: entryCount, - }; - - // Mock Grpc layer - client._innerApiCalls.createGlossary = mockLongRunningGrpcMethod( - request, - expectedResponse - ); - - client - .createGlossary(request) - .then(responses => { - const operation = responses[0]; - return operation.promise(); - }) - .then(responses => { - assert.deepStrictEqual(responses[0], expectedResponse); - done(); - }) - .catch(err => { - done(err); - }); - }); - - it('invokes createGlossary with error', done => { - const client = new translateModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - - // Mock request - const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); - const glossary = {}; - const request = { - parent: formattedParent, - glossary: glossary, - }; - - // Mock Grpc layer - client._innerApiCalls.createGlossary = mockLongRunningGrpcMethod( - request, - null, - error - ); - - client - .createGlossary(request) - .then(responses => { - const operation = responses[0]; - return operation.promise(); - }) - .then(() => { - assert.fail(); - }) - .catch(err => { - assert(err instanceof Error); - assert.strictEqual(err.code, FAKE_STATUS_CODE); - done(); - }); - }); - - it('has longrunning decoder functions', () => { - const client = new translateModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert( - client._descriptors.longrunning.createGlossary - .responseDecoder instanceof Function - ); - assert( - client._descriptors.longrunning.createGlossary - .metadataDecoder instanceof Function - ); - }); - }); - - describe('listGlossaries', () => { - it('invokes listGlossaries without error', done => { - const client = new translateModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - - // Mock request - const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); - const request = { - parent: formattedParent, - }; - - // Mock response - const nextPageToken = ''; - const glossariesElement = {}; - const glossaries = [glossariesElement]; - const expectedResponse = { - nextPageToken: nextPageToken, - glossaries: glossaries, - }; - - // Mock Grpc layer - client._innerApiCalls.listGlossaries = ( - actualRequest, - options, - callback - ) => { - assert.deepStrictEqual(actualRequest, request); - callback(null, expectedResponse.glossaries); - }; - - client.listGlossaries(request, (err, response) => { - assert.ifError(err); - assert.deepStrictEqual(response, expectedResponse.glossaries); - done(); - }); - }); - - it('invokes listGlossaries with error', done => { - const client = new translateModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - - // Mock request - const formattedParent = client.locationPath('[PROJECT]', '[LOCATION]'); - const request = { - parent: formattedParent, - }; - - // Mock Grpc layer - client._innerApiCalls.listGlossaries = mockSimpleGrpcMethod( - request, - null, - error - ); - - client.listGlossaries(request, (err, response) => { - assert(err instanceof Error); - assert.strictEqual(err.code, FAKE_STATUS_CODE); - assert(typeof response === 'undefined'); - done(); - }); - }); - }); - - describe('getGlossary', () => { - it('invokes getGlossary without error', done => { - const client = new translateModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - - // Mock request - const formattedName = client.glossaryPath( - '[PROJECT]', - '[LOCATION]', - '[GLOSSARY]' - ); - const request = { - name: formattedName, - }; - - // Mock response - const name2 = 'name2-1052831874'; - const entryCount = 811131134; - const expectedResponse = { - name: name2, - entryCount: entryCount, - }; - - // Mock Grpc layer - client._innerApiCalls.getGlossary = mockSimpleGrpcMethod( - request, - expectedResponse - ); - - client.getGlossary(request, (err, response) => { - assert.ifError(err); - assert.deepStrictEqual(response, expectedResponse); - done(); - }); - }); - - it('invokes getGlossary with error', done => { - const client = new translateModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - - // Mock request - const formattedName = client.glossaryPath( - '[PROJECT]', - '[LOCATION]', - '[GLOSSARY]' - ); - const request = { - name: formattedName, - }; - - // Mock Grpc layer - client._innerApiCalls.getGlossary = mockSimpleGrpcMethod( - request, - null, - error - ); - - client.getGlossary(request, (err, response) => { - assert(err instanceof Error); - assert.strictEqual(err.code, FAKE_STATUS_CODE); - assert(typeof response === 'undefined'); - done(); - }); - }); - }); - - describe('deleteGlossary', function() { - it('invokes deleteGlossary without error', done => { - const client = new translateModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - - // Mock request - const formattedName = client.glossaryPath( - '[PROJECT]', - '[LOCATION]', - '[GLOSSARY]' - ); - const request = { - name: formattedName, - }; - - // Mock response - const name2 = 'name2-1052831874'; - const expectedResponse = { - name: name2, - }; - - // Mock Grpc layer - client._innerApiCalls.deleteGlossary = mockLongRunningGrpcMethod( - request, - expectedResponse - ); - - client - .deleteGlossary(request) - .then(responses => { - const operation = responses[0]; - return operation.promise(); - }) - .then(responses => { - assert.deepStrictEqual(responses[0], expectedResponse); - done(); - }) - .catch(err => { - done(err); - }); - }); - - it('invokes deleteGlossary with error', done => { - const client = new translateModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - - // Mock request - const formattedName = client.glossaryPath( - '[PROJECT]', - '[LOCATION]', - '[GLOSSARY]' - ); - const request = { - name: formattedName, - }; - - // Mock Grpc layer - client._innerApiCalls.deleteGlossary = mockLongRunningGrpcMethod( - request, - null, - error - ); - - client - .deleteGlossary(request) - .then(responses => { - const operation = responses[0]; - return operation.promise(); - }) - .then(() => { - assert.fail(); - }) - .catch(err => { - assert(err instanceof Error); - assert.strictEqual(err.code, FAKE_STATUS_CODE); - done(); - }); - }); - - it('has longrunning decoder functions', () => { - const client = new translateModule.v3beta1.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert( - client._descriptors.longrunning.deleteGlossary - .responseDecoder instanceof Function - ); - assert( - client._descriptors.longrunning.deleteGlossary - .metadataDecoder instanceof Function - ); - }); - }); -}); - -function mockSimpleGrpcMethod(expectedRequest, response, error) { - return function(actualRequest, options, callback) { - assert.deepStrictEqual(actualRequest, expectedRequest); - if (error) { - callback(error); - } else if (response) { - callback(null, response); - } else { - callback(null); - } - }; -} - -function mockLongRunningGrpcMethod(expectedRequest, response, error) { - return request => { - assert.deepStrictEqual(request, expectedRequest); - const mockOperation = { - promise: function() { - return new Promise((resolve, reject) => { - if (error) { - reject(error); - } else { - resolve([response]); - } - }); - }, - }; - return Promise.resolve([mockOperation]); - }; -}