diff --git a/.eslintrc.json b/.eslintrc.json new file mode 100644 index 00000000..78215349 --- /dev/null +++ b/.eslintrc.json @@ -0,0 +1,3 @@ +{ + "extends": "./node_modules/gts" +} diff --git a/.eslintrc.yml b/.eslintrc.yml deleted file mode 100644 index 73eeec27..00000000 --- a/.eslintrc.yml +++ /dev/null @@ -1,15 +0,0 @@ ---- -extends: - - 'eslint:recommended' - - 'plugin:node/recommended' - - prettier -plugins: - - node - - prettier -rules: - prettier/prettier: error - block-scoped-var: error - eqeqeq: error - no-warning-comments: warn - no-var: error - prefer-const: error diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 92394b1e..7138a79a 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -9,7 +9,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - node: [8, 10, 12, 13] + node: [10, 12, 13] steps: - uses: actions/checkout@v2 - uses: actions/setup-node@v1 diff --git a/.prettierrc b/.prettierrc deleted file mode 100644 index df6eac07..00000000 --- a/.prettierrc +++ /dev/null @@ -1,8 +0,0 @@ ---- -bracketSpacing: false -printWidth: 80 -semi: true -singleQuote: true -tabWidth: 2 -trailingComma: es5 -useTabs: false diff --git a/.prettierrc.js b/.prettierrc.js new file mode 100644 index 00000000..08cba377 --- /dev/null +++ b/.prettierrc.js @@ -0,0 +1,17 @@ +// Copyright 2020 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. + +module.exports = { + ...require('gts/.prettierrc.json') +} diff --git a/package.json b/package.json index b3d7baa8..53d677df 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,7 @@ "license": "Apache-2.0", "author": "Google Inc.", "engines": { - "node": ">=8.10.0" + "node": ">=10" }, "repository": "googleapis/nodejs-translate", "main": "build/src/index.js", @@ -48,7 +48,7 @@ "@google-cloud/promisify": "^1.0.0", "arrify": "^2.0.0", "extend": "^3.0.2", - "google-gax": "^1.11.1", + "google-gax": "^2.0.1", "is-html": "^2.0.0", "protobufjs": "^6.8.8" }, @@ -58,6 +58,7 @@ "@types/node": "^10.5.7", "@types/proxyquire": "^1.3.28", "@types/request": "^2.47.1", + "@types/sinon": "^7.5.2", "c8": "^7.0.0", "codecov": "^3.0.2", "eslint": "^6.0.0", @@ -65,7 +66,7 @@ "eslint-plugin-node": "^11.0.0", "eslint-plugin-prettier": "^3.0.0", "google-auth-library": "^5.7.0", - "gts": "^1.0.0", + "gts": "2.0.0-alpha.9", "http2spy": "^1.1.0", "jsdoc": "^3.6.2", "jsdoc-fresh": "^1.0.1", @@ -75,6 +76,7 @@ "pack-n-play": "^1.0.0-2", "prettier": "^1.13.5", "proxyquire": "^2.0.1", - "typescript": "3.6.4" + "sinon": "^9.0.1", + "typescript": "^3.8.3" } } diff --git a/samples/automl/automlTranslationDataset.js b/samples/automl/automlTranslationDataset.js index 0d1fc80d..46d1c1af 100644 --- a/samples/automl/automlTranslationDataset.js +++ b/samples/automl/automlTranslationDataset.js @@ -24,7 +24,7 @@ async function createDataset(projectId) { // [START automl_translation_create_dataset] - const automl = require(`@google-cloud/automl`); + const automl = require('@google-cloud/automl'); const client = new automl.AutoMlClient(); const computeRegion = 'us-central1'; @@ -55,17 +55,17 @@ async function createDataset(projectId) { // Display the dataset information console.log(`Dataset name: ${dataset.name}`); - console.log(`Dataset id: ${dataset.name.split(`/`).pop(-1)}`); + console.log(`Dataset id: ${dataset.name.split('/').pop(-1)}`); console.log(`Dataset display name: ${dataset.displayName}`); console.log(`Dataset example count: ${dataset.exampleCount}`); - console.log(`Translation dataset specification:`); + console.log('Translation dataset specification:'); console.log( `\tSource language code: ${dataset.translationDatasetMetadata.sourceLanguageCode}` ); console.log( `\tTarget language code: ${dataset.translationDatasetMetadata.targetLanguageCode}` ); - console.log(`Dataset create time:`); + console.log('Dataset create time:'); console.log(`\tseconds: ${dataset.createTime.seconds}`); console.log(`\tnanos: ${dataset.createTime.nanos}`); // [END automl_translation_create_dataset] @@ -73,7 +73,7 @@ async function createDataset(projectId) { async function listDatasets(projectId, computeRegion, filter) { // [START automl_translation_list_datasets] - const automl = require(`@google-cloud/automl`); + const automl = require('@google-cloud/automl'); const client = new automl.AutoMlClient(); /** @@ -97,20 +97,20 @@ async function listDatasets(projectId, computeRegion, filter) { console.log('No datasets found!'); return; } - console.log(`List of datasets:`); + console.log('List of datasets:'); datasets.forEach(dataset => { console.log(`Dataset name: ${dataset.name}`); - console.log(`Dataset id: ${dataset.name.split(`/`).pop(-1)}`); + console.log(`Dataset id: ${dataset.name.split('/').pop(-1)}`); console.log(`Dataset display name: ${dataset.displayName}`); console.log(`Dataset example count: ${dataset.exampleCount}`); - console.log(`Translation dataset specification:`); + console.log('Translation dataset specification:'); console.log( `\tSource language code: ${dataset.translationDatasetMetadata.sourceLanguageCode}` ); console.log( `\tTarget language code: ${dataset.translationDatasetMetadata.targetLanguageCode}` ); - console.log(`Dataset create time:`); + console.log('Dataset create time:'); console.log(`\tseconds: ${dataset.createTime.seconds}`); console.log(`\tnanos: ${dataset.createTime.nanos}`); }); @@ -119,7 +119,7 @@ async function listDatasets(projectId, computeRegion, filter) { async function getDataset(projectId, computeRegion, datasetId) { // [START automl_translation_get_dataset] - const automl = require(`@google-cloud/automl`); + const automl = require('@google-cloud/automl'); const client = new automl.AutoMlClient(); /** @@ -137,17 +137,17 @@ async function getDataset(projectId, computeRegion, datasetId) { // Display the dataset information. console.log(`Dataset name: ${dataset.name}`); - console.log(`Dataset id: ${dataset.name.split(`/`).pop(-1)}`); + console.log(`Dataset id: ${dataset.name.split('/').pop(-1)}`); console.log(`Dataset display name: ${dataset.displayName}`); console.log(`Dataset example count: ${dataset.exampleCount}`); - console.log(`Translation dataset specification:`); + console.log('Translation dataset specification:'); console.log( `\tSource language code: ${dataset.translationDatasetMetadata.sourceLanguageCode}` ); console.log( `\tTarget language code: ${dataset.translationDatasetMetadata.targetLanguageCode}` ); - console.log(`Dataset create time:`); + console.log('Dataset create time:'); console.log(`\tseconds: ${dataset.createTime.seconds}`); console.log(`\tnanos: ${dataset.createTime.nanos}`); @@ -156,7 +156,7 @@ async function getDataset(projectId, computeRegion, datasetId) { async function importData(projectId, computeRegion, datasetId, path) { // [START automl_translation_import_data] - const automl = require(`@google-cloud/automl`); + const automl = require('@google-cloud/automl'); const client = new automl.AutoMlClient(); @@ -172,7 +172,7 @@ async function importData(projectId, computeRegion, datasetId, path) { const datasetFullId = client.datasetPath(projectId, computeRegion, datasetId); // Get the multiple Google Cloud Storage URIs. - const inputUris = path.split(`,`); + const inputUris = path.split(','); const inputConfig = { gcsSource: { inputUris: inputUris, @@ -184,11 +184,11 @@ async function importData(projectId, computeRegion, datasetId, path) { name: datasetFullId, inputConfig: inputConfig, }); - console.log(`Processing import...`); + console.log('Processing import...'); const operationResponses = await operation.promise(); // The final result of the operation. if (operationResponses[2].done === true) { - console.log(`Data imported.`); + console.log('Data imported.'); } // [END automl_translation_import_data] @@ -196,7 +196,7 @@ async function importData(projectId, computeRegion, datasetId, path) { async function deleteDataset(projectId, computeRegion, datasetId) { // [START automl_translation_delete_dataset] - const automl = require(`@google-cloud/automl`); + const automl = require('@google-cloud/automl'); const client = new automl.AutoMlClient(); /** @@ -213,85 +213,85 @@ async function deleteDataset(projectId, computeRegion, datasetId) { const [operations] = await client.deleteDataset({name: datasetFullId}); const operationResponses = await operations.promise(); // The final result of the operation. - if (operationResponses[2].done === true) console.log(`Dataset deleted.`); + if (operationResponses[2].done === true) console.log('Dataset deleted.'); // [END automl_translation_delete_dataset] } -require(`yargs`) +require('yargs') .demand(1) .options({ computeRegion: { - alias: `c`, - type: `string`, + alias: 'c', + type: 'string', default: 'us-central1', requiresArg: true, - description: `region name e.g. "us-central1"`, + description: 'region name e.g. "us-central1"', }, datasetName: { - alias: `n`, - type: `string`, - default: `testDataSet`, + alias: 'n', + type: 'string', + default: 'testDataSet', requiresArg: true, - description: `Name of the Dataset`, + description: 'Name of the Dataset', }, datasetId: { - alias: `i`, - type: `string`, + alias: 'i', + type: 'string', requiresArg: true, - description: `Id of the dataset`, + description: 'Id of the dataset', }, filter: { - alias: `f`, - default: `translationDatasetMetadata:*`, - type: `string`, + alias: 'f', + default: 'translationDatasetMetadata:*', + type: 'string', requiresArg: true, - description: `Name of the Dataset to search for`, + description: 'Name of the Dataset to search for', }, multilabel: { - alias: `m`, - type: `string`, + alias: 'm', + type: 'string', default: false, requiresArg: true, description: - `Type of the classification problem, ` + - `False - MULTICLASS, True - MULTILABEL.`, + 'Type of the classification problem, ' + + 'False - MULTICLASS, True - MULTILABEL.', }, outputUri: { - alias: `o`, - type: `string`, + alias: 'o', + type: 'string', requiresArg: true, - description: `URI (or local path) to export dataset`, + description: 'URI (or local path) to export dataset', }, path: { - alias: `p`, - type: `string`, + alias: 'p', + type: 'string', global: true, - default: `gs://nodejs-docs-samples-vcm/en-ja.csv`, + default: 'gs://nodejs-docs-samples-vcm/en-ja.csv', requiresArg: true, - description: `URI or local path to input .csv, or array of .csv paths`, + description: 'URI or local path to input .csv, or array of .csv paths', }, projectId: { - alias: `z`, - type: `number`, + alias: 'z', + type: 'number', default: process.env.GCLOUD_PROJECT, requiresArg: true, - description: `The GCLOUD_PROJECT string, e.g. "my-gcloud-project"`, + description: 'The GCLOUD_PROJECT string, e.g. "my-gcloud-project"', }, source: { - alias: `s`, - type: `string`, + alias: 's', + type: 'string', requiresArg: true, - description: `The source language to be translated from`, + description: 'The source language to be translated from', }, target: { - alias: `t`, - type: `string`, + alias: 't', + type: 'string', requiresArg: true, - description: `The target language to be translated to`, + description: 'The target language to be translated to', }, }) - .command(`createDataset`, `creates a new Dataset`, {}, opts => + .command('createDataset', 'creates a new Dataset', {}, opts => createDataset( opts.projectId, opts.computeRegion, @@ -300,24 +300,24 @@ require(`yargs`) opts.target ) ) - .command(`list-datasets`, `list all Datasets`, {}, opts => + .command('list-datasets', 'list all Datasets', {}, opts => listDatasets(opts.projectId, opts.computeRegion, opts.filter) ) - .command(`get-dataset`, `Get a Dataset`, {}, opts => + .command('get-dataset', 'Get a Dataset', {}, opts => getDataset(opts.projectId, opts.computeRegion, opts.datasetId) ) - .command(`delete-dataset`, `Delete a dataset`, {}, opts => + .command('delete-dataset', 'Delete a dataset', {}, opts => deleteDataset(opts.projectId, opts.computeRegion, opts.datasetId) ) - .command(`import-data`, `Import labeled items into dataset`, {}, opts => + .command('import-data', 'Import labeled items into dataset', {}, opts => importData(opts.projectId, opts.computeRegion, opts.datasetId, opts.path) ) - .example(`node $0 create-dataset -n "newDataSet" -s "en" -t "ja"`) - .example(`node $0 list-datasets -f "translationDatasetMetadata:*"`) - .example(`node $0 get-dataset -i "DATASETID"`) - .example(`node $0 delete-dataset -i "DATASETID"`) + .example('node $0 create-dataset -n "newDataSet" -s "en" -t "ja"') + .example('node $0 list-datasets -f "translationDatasetMetadata:*"') + .example('node $0 get-dataset -i "DATASETID"') + .example('node $0 delete-dataset -i "DATASETID"') .example( - `node $0 import-data -i "dataSetId" -p "gs://myproject/mytraindata.csv"` + 'node $0 import-data -i "dataSetId" -p "gs://myproject/mytraindata.csv"' ) .wrap(120) .recommendCommands() diff --git a/samples/automl/automlTranslationModel.js b/samples/automl/automlTranslationModel.js index 61aa421d..cf7dcba2 100644 --- a/samples/automl/automlTranslationModel.js +++ b/samples/automl/automlTranslationModel.js @@ -24,7 +24,7 @@ async function createModel(projectId, computeRegion, datasetId, modelName) { // [START automl_translation_create_model] - const automl = require(`@google-cloud/automl`); + const automl = require('@google-cloud/automl'); const client = new automl.AutoMlClient(); @@ -52,24 +52,24 @@ async function createModel(projectId, computeRegion, datasetId, modelName) { model: myModel, }); const initialApiResponse = response; - console.log(`Training operation name: `, initialApiResponse.name); - console.log(`Training started...`); + console.log('Training operation name: ', initialApiResponse.name); + console.log('Training started...'); const [model] = await operation.promise(); // The final result of the operation. console.log(model); // Retrieve deployment state. - let deploymentState = ``; + let deploymentState = ''; if (model.deploymentState === 1) { - deploymentState = `deployed`; + deploymentState = 'deployed'; } else if (model.deploymentState === 2) { - deploymentState = `undeployed`; + deploymentState = 'undeployed'; } // Display the model information. console.log(`Model name: ${model.name}`); - console.log(`Model id: ${model.name.split(`/`).pop(-1)}`); + console.log(`Model id: ${model.name.split('/').pop(-1)}`); console.log(`Model display name: ${model.displayName}`); - console.log(`Model create time:`); + console.log('Model create time:'); console.log(`\tseconds: ${model.createTime.seconds}`); console.log(`\tnanos: ${model.createTime.nanos}`); console.log(`Model deployment state: ${deploymentState}`); @@ -79,7 +79,7 @@ async function createModel(projectId, computeRegion, datasetId, modelName) { async function listModels(projectId, computeRegion, filter) { // [START automl_translation_list_models] - const automl = require(`@google-cloud/automl`); + const automl = require('@google-cloud/automl'); const client = new automl.AutoMlClient(); @@ -100,20 +100,20 @@ async function listModels(projectId, computeRegion, filter) { }); // Display the model information. - console.log(`List of models:`); + console.log('List of models:'); models.forEach(model => { console.log(`Model name: ${model.name}`); - console.log(`Model id: ${model.name.split(`/`).pop(-1)}`); + console.log(`Model id: ${model.name.split('/').pop(-1)}`); console.log(`Model display name: ${model.displayName}`); console.log(`Model dataset id: ${model.datasetId}`); - console.log(`Model create time:`); + console.log('Model create time:'); console.log(`\tseconds: ${model.createTime.seconds}`); console.log(`\tnanos: ${model.createTime.nanos}`); - console.log(`Model update time:`); + console.log('Model update time:'); console.log(`\tseconds: ${model.updateTime.seconds}`); console.log(`\tnanos: ${model.updateTime.nanos}`); console.log(`Model deployment state: ${model.deploymentState}`); - console.log(`\n`); + console.log('\n'); }); // [END automl_translation_list_models] @@ -121,7 +121,7 @@ async function listModels(projectId, computeRegion, filter) { async function getModel(projectId, computeRegion, modelId) { // [START automl_translation_get_model] - const automl = require(`@google-cloud/automl`); + const automl = require('@google-cloud/automl'); const client = new automl.AutoMlClient(); @@ -140,11 +140,11 @@ async function getModel(projectId, computeRegion, modelId) { // Display the model information. console.log(`Model name: ${model.name}`); - console.log(`Model id: ${model.name.split(`/`).pop(-1)}`); + console.log(`Model id: ${model.name.split('/').pop(-1)}`); console.log(`Model display name: ${model.displayName}`); console.log(`Model dataset id: ${model.datasetId}`); - if (model.modelMetadata === `translationModelMetadata`) { - console.log(`Translation model metadata:`); + if (model.modelMetadata === 'translationModelMetadata') { + console.log('Translation model metadata:'); console.log(`\tBase model: ${model.translationModelMetadata.baseModel}`); console.log( `\tSource language code: ${model.translationModelMetadata.sourceLanguageCode}` @@ -152,12 +152,12 @@ async function getModel(projectId, computeRegion, modelId) { console.log( `\tTarget language code: ${model.translationModelMetadata.targetLanguageCode}` ); - } else if (model.modelMetadata === `textClassificationModelMetadata`) { + } else if (model.modelMetadata === 'textClassificationModelMetadata') { console.log( `Text classification model metadata: ${model.textClassificationModelMetadata}` ); - } else if (model.modelMetadata === `imageClassificationModelMetadata`) { - console.log(`Image classification model metadata:`); + } else if (model.modelMetadata === 'imageClassificationModelMetadata') { + console.log('Image classification model metadata:'); console.log( `\tBase model id: ${model.imageClassificationModelMetadata.baseModelId}` ); @@ -171,10 +171,10 @@ async function getModel(projectId, computeRegion, modelId) { `\tStop reason: ${model.imageClassificationModelMetadata.stopReason}` ); } - console.log(`Model create time:`); + console.log('Model create time:'); console.log(`\tseconds: ${model.createTime.seconds}`); console.log(`\tnanos: ${model.createTime.nanos}`); - console.log(`Model update time:`); + console.log('Model update time:'); console.log(`\tseconds: ${model.updateTime.seconds}`); console.log(`\tnanos: ${model.updateTime.nanos}`); console.log(`Model deployment state: ${model.deploymentState}`); @@ -184,7 +184,7 @@ async function getModel(projectId, computeRegion, modelId) { async function listModelEvaluations(projectId, computeRegion, modelId, filter) { // [START automl_translation_list_model_evaluations] - const automl = require(`@google-cloud/automl`); + const automl = require('@google-cloud/automl'); const client = new automl.AutoMlClient(); @@ -204,7 +204,7 @@ async function listModelEvaluations(projectId, computeRegion, modelId, filter) { parent: modelFullId, filter: filter, }); - console.log(`List of model evaluations:`); + console.log('List of model evaluations:'); elements.forEach(element => { console.log(element); }); @@ -219,7 +219,7 @@ async function getModelEvaluation( modelEvaluationId ) { // [START automl_translation_get_model_evaluation] - const automl = require(`@google-cloud/automl`); + const automl = require('@google-cloud/automl'); const client = new automl.AutoMlClient(); /** @@ -249,7 +249,7 @@ async function getModelEvaluation( async function deleteModel(projectId, computeRegion, modelId) { // [START automl_translation_delete_model] - const automl = require(`@google-cloud/automl`); + const automl = require('@google-cloud/automl'); const client = new automl.AutoMlClient(); @@ -267,14 +267,14 @@ async function deleteModel(projectId, computeRegion, modelId) { const [operation] = await client.deleteModel({name: modelFullId}); const operationResponse = await operation.promise(); // The final result of the operation. - if (operationResponse[2].done === true) console.log(`Model deleted.`); + if (operationResponse[2].done === true) console.log('Model deleted.'); // [END automl_translation_delete_model] } async function getOperationStatus(operationFullId) { // [START automl_translation_get_operation_status] - const automl = require(`@google-cloud/automl`); + const automl = require('@google-cloud/automl'); const client = new automl.AutoMlClient(); @@ -291,66 +291,66 @@ async function getOperationStatus(operationFullId) { // [END automl_translation_get_operation_status] } -require(`yargs`) +require('yargs') .demand(1) .options({ computeRegion: { - alias: `c`, - type: `string`, + alias: 'c', + type: 'string', default: 'us-central1', requiresArg: true, - description: `region name e.g. "us-central1"`, + description: 'region name e.g. "us-central1"', }, datasetId: { - alias: `i`, - type: `string`, + alias: 'i', + type: 'string', requiresArg: true, - description: `Id of the dataset`, + description: 'Id of the dataset', }, filter: { - alias: `f`, - default: ``, - type: `string`, + alias: 'f', + default: '', + type: 'string', requiresArg: true, - description: `Name of the Dataset to search for`, + description: 'Name of the Dataset to search for', }, modelName: { - alias: `m`, - type: `string`, + alias: 'm', + type: 'string', default: false, requiresArg: true, - description: `Name of the model`, + description: 'Name of the model', }, modelId: { - alias: `a`, - type: `string`, - default: ``, + alias: 'a', + type: 'string', + default: '', requiresArg: true, - description: `Id of the model`, + description: 'Id of the model', }, modelEvaluationId: { - alias: `e`, - type: `string`, - default: ``, + alias: 'e', + type: 'string', + default: '', requiresArg: true, - description: `Id of the model evaluation`, + description: 'Id of the model evaluation', }, operationFullId: { - alias: `o`, - type: `string`, - default: ``, + alias: 'o', + type: 'string', + default: '', requiresArg: true, - description: `Full name of an operation`, + description: 'Full name of an operation', }, projectId: { - alias: `z`, - type: `number`, + alias: 'z', + type: 'number', default: process.env.GCLOUD_PROJECT, requiresArg: true, - description: `The GCLOUD_PROJECT string, e.g. "my-gcloud-project"`, + description: 'The GCLOUD_PROJECT string, e.g. "my-gcloud-project"', }, }) - .command(`create-model`, `creates a new Model`, {}, opts => + .command('create-model', 'creates a new Model', {}, opts => createModel( opts.projectId, opts.computeRegion, @@ -359,18 +359,18 @@ require(`yargs`) ) ) .command( - `get-operation-status`, - `Gets status of current operation`, + 'get-operation-status', + 'Gets status of current operation', {}, opts => getOperationStatus(opts.operationFullId) ) - .command(`list-models`, `list all Models`, {}, opts => + .command('list-models', 'list all Models', {}, opts => listModels(opts.projectId, opts.computeRegion, opts.filter) ) - .command(`get-model`, `Get a Model`, {}, opts => + .command('get-model', 'Get a Model', {}, opts => getModel(opts.projectId, opts.computeRegion, opts.modelId) ) - .command(`list-model-evaluations`, `List model evaluations`, {}, opts => + .command('list-model-evaluations', 'List model evaluations', {}, opts => listModelEvaluations( opts.projectId, opts.computeRegion, @@ -378,7 +378,7 @@ require(`yargs`) opts.filter ) ) - .command(`get-model-evaluation`, `Get model evaluation`, {}, opts => + .command('get-model-evaluation', 'Get model evaluation', {}, opts => getModelEvaluation( opts.projectId, opts.computeRegion, @@ -386,16 +386,16 @@ require(`yargs`) opts.modelEvaluationId ) ) - .command(`delete-model`, `Delete a Model`, {}, opts => + .command('delete-model', 'Delete a Model', {}, opts => deleteModel(opts.projectId, opts.computeRegion, opts.modelId) ) - .example(`node $0 create-model -i "DatasetID" -m "myModelName"`) - .example(`node $0 get-operation-status -i "datasetId" -o "OperationFullID"`) - .example(`node $0 list-models -f "translationModelMetadata:*"`) - .example(`node $0 get-model -a "ModelID"`) - .example(`node $0 list-model-evaluations -a "ModelID"`) - .example(`node $0 get-model-evaluation -a "ModelId" -e "ModelEvaluationID"`) - .example(`node $0 delete-model -a "ModelID"`) + .example('node $0 create-model -i "DatasetID" -m "myModelName"') + .example('node $0 get-operation-status -i "datasetId" -o "OperationFullID"') + .example('node $0 list-models -f "translationModelMetadata:*"') + .example('node $0 get-model -a "ModelID"') + .example('node $0 list-model-evaluations -a "ModelID"') + .example('node $0 get-model-evaluation -a "ModelId" -e "ModelEvaluationID"') + .example('node $0 delete-model -a "ModelID"') .wrap(120) .recommendCommands() .help() diff --git a/samples/automl/automlTranslationPredict.js b/samples/automl/automlTranslationPredict.js index ccd37f88..2630b781 100644 --- a/samples/automl/automlTranslationPredict.js +++ b/samples/automl/automlTranslationPredict.js @@ -30,8 +30,8 @@ async function predict( translationAllowFallback ) { // [START automl_translation_predict] - const automl = require(`@google-cloud/automl`); - const fs = require(`fs`); + const automl = require('@google-cloud/automl'); + const fs = require('fs'); // Create client for prediction service. const client = new automl.PredictionServiceClient(); @@ -49,7 +49,7 @@ async function predict( const modelFullId = client.modelPath(projectId, computeRegion, modelId); // Read the file content for translation. - const content = fs.readFileSync(filePath, `utf8`); + const content = fs.readFileSync(filePath, 'utf8'); // Set the payload by giving the content of the file. const payload = { @@ -75,55 +75,55 @@ async function predict( const response = responses[0]; console.log( - `Translated Content: `, + 'Translated Content: ', response.payload[0].translation.translatedContent.content ); // [END automl_translation_predict] } -require(`yargs`) +require('yargs') .demand(1) .options({ computeRegion: { - alias: `c`, - type: `string`, + alias: 'c', + type: 'string', default: 'us-central1', requiresArg: true, - description: `region name e.g. "us-central1"`, + description: 'region name e.g. "us-central1"', }, filePath: { - alias: `f`, - default: `./resources/testInput.txt`, - type: `string`, + alias: 'f', + default: './resources/testInput.txt', + type: 'string', requiresArg: true, - description: `local text file path of the content to be classified`, + description: 'local text file path of the content to be classified', }, modelId: { - alias: `i`, - type: `string`, + alias: 'i', + type: 'string', requiresArg: true, - description: `Id of the model which will be used for text classification`, + description: 'Id of the model which will be used for text classification', }, projectId: { - alias: `z`, - type: `number`, + alias: 'z', + type: 'number', default: process.env.GCLOUD_PROJECT, requiresArg: true, - description: `The GCLOUD_PROJECT string, e.g. "my-gcloud-project"`, + description: 'The GCLOUD_PROJECT string, e.g. "my-gcloud-project"', }, translationAllowFallback: { - alias: `t`, - type: `string`, - default: `False`, + alias: 't', + type: 'string', + default: 'False', requiresArg: true, description: - `Use true if AutoML will fallback to use a Google translation model for` + - `translation requests if the specified AutoML translation model cannot` + - `serve the request. Use false to not use Google translation model.`, + 'Use true if AutoML will fallback to use a Google translation model for' + + 'translation requests if the specified AutoML translation model cannot' + + 'serve the request. Use false to not use Google translation model.', }, }) - .command(`predict`, `classify the content`, {}, opts => + .command('predict', 'classify the content', {}, opts => predict( opts.projectId, opts.computeRegion, @@ -133,7 +133,7 @@ require(`yargs`) ) ) .example( - `node $0 predict -i "modelId" -f "./resources/testInput.txt" -t "False"` + 'node $0 predict -i "modelId" -f "./resources/testInput.txt" -t "False"' ) .wrap(120) .recommendCommands() diff --git a/samples/hybridGlossaries.js b/samples/hybridGlossaries.js index ffcdfece..c800b0fc 100644 --- a/samples/hybridGlossaries.js +++ b/samples/hybridGlossaries.js @@ -102,7 +102,7 @@ async function main( const [operation] = await translationClient.createGlossary(request); // Wait for operation to complete. await operation.promise(); - console.log(`Created glossary ` + glossaryName + '.'); + console.log('Created glossary ' + glossaryName + '.'); } catch (AlreadyExists) { console.log( 'The glossary ' + diff --git a/samples/test/automlTranslation.test.js b/samples/test/automlTranslation.test.js index f73ee85c..38118c96 100644 --- a/samples/test/automlTranslation.test.js +++ b/samples/test/automlTranslation.test.js @@ -31,7 +31,7 @@ const sampleText = './resources/testInput.txt'; const donotdeleteModelId = 'TRL188026453969732486'; describe.skip('automl sample tests', () => { - it(`should create a create, list, and delete a dataset`, async () => { + it('should create a create, list, and delete a dataset', async () => { // Check to see that this dataset does not yet exist let output = execSync(`${cmdDataset} list-datasets`); assert.match(output, new RegExp(testDataSetName)); @@ -39,8 +39,8 @@ describe.skip('automl sample tests', () => { // Create dataset output = execSync(`${cmdDataset} create-dataset -n "${testDataSetName}"`); const dataSetId = output - .split(`\n`)[1] - .split(`:`)[1] + .split('\n')[1] + .split(':')[1] .trim(); assert.match( output, @@ -53,7 +53,7 @@ describe.skip('automl sample tests', () => { }); // We make two models running this test, see hard-coded workaround below - it(`should create a dataset, import data, and start making a model`, async () => { + it('should create a dataset, import data, and start making a model', async () => { // Check to see that this dataset does not yet exist let output = execSync(`${cmdDataset} list-datasets`); assert.notMatch(output, new RegExp(dummyDataSet)); @@ -61,8 +61,8 @@ describe.skip('automl sample tests', () => { // Create dataset output = execSync(`${cmdDataset} create-dataset -n "${dummyDataSet}"`); const dataSetId = output - .split(`\n`)[1] - .split(`:`)[1] + .split('\n')[1] + .split(':')[1] .trim(); assert.match(output, new RegExp(`Dataset display name: ${dummyDataSet}`)); @@ -81,10 +81,10 @@ describe.skip('automl sample tests', () => { `${cmdModel} create-model -i "${dataSetId}" -m "${testModelName}" -t "2"` ); const operationName = output - .split(`\n`)[0] - .split(`:`)[1] + .split('\n')[0] + .split(':')[1] .trim(); - assert.match(output, `Training started...`); + assert.match(output, 'Training started...'); // Poll operation status, here confirming that operation is not complete yet output = execSync( @@ -93,7 +93,7 @@ describe.skip('automl sample tests', () => { assert.match(output, /done: false/); }); - it(`should run get model (from a prexisting model)`, async () => { + it('should run get model (from a prexisting model)', async () => { // Confirm dataset exists let output = execSync(`${cmdDataset} list-datasets`); assert.match(output, /me_do_not_delete/); @@ -109,7 +109,7 @@ describe.skip('automl sample tests', () => { assert.match(output, /Model deployment state: DEPLOYED/); }); - it(`should run Prediction from prexisting model`, async () => { + it('should run Prediction from prexisting model', async () => { // Confirm dataset exists let output = execSync(`${cmdDataset} list-datasets`); assert.match(output, /me_do_not_delete/); @@ -118,7 +118,7 @@ describe.skip('automl sample tests', () => { output = execSync( `${cmdModel} list-model-evaluations -a "${donotdeleteModelId}"` ); - assert.match(output, `translationEvaluationMetrics:`); + assert.match(output, 'translationEvaluationMetrics:'); // Run prediction on 'testImage.jpg' in resources folder output = execSync( @@ -131,7 +131,7 @@ describe.skip('automl sample tests', () => { }); // List datasets - it(`should list datasets`, async () => { + it('should list datasets', async () => { const output = execSync(`${cmdDataset} list-datasets`); assert.match(output, /List of datasets:/); }); diff --git a/samples/test/hybridGlossaries.test.js b/samples/test/hybridGlossaries.test.js index 02633336..3623266f 100644 --- a/samples/test/hybridGlossaries.test.js +++ b/samples/test/hybridGlossaries.test.js @@ -48,7 +48,7 @@ describe(REGION_TAG, () => { assert.strictEqual(fs.existsSync(outputFile), true); }); - after(async function() { + after(async () => { fs.unlinkSync(outputFile); assert.strictEqual(fs.existsSync(outputFile), false); // get projectId diff --git a/samples/test/translate.test.js b/samples/test/translate.test.js index 02307c58..0124c2fb 100644 --- a/samples/test/translate.test.js +++ b/samples/test/translate.test.js @@ -49,13 +49,13 @@ describe('translate sample tests', () => { it('should list languages', () => { const output = execSync(`${cmd} list`); assert.match(output, /Languages:/); - assert.match(output, new RegExp(`{ code: 'af', name: 'Afrikaans' }`)); + assert.match(output, new RegExp("{ code: 'af', name: 'Afrikaans' }")); }); it('should list languages with a target', () => { const output = execSync(`${cmd} list es`); assert.match(output, /Languages:/); - assert.match(output, new RegExp(`{ code: 'af', name: 'afrikáans' }`)); + assert.match(output, new RegExp("{ code: 'af', name: 'afrikáans' }")); }); it('should translate a single string', async () => { diff --git a/samples/test/v3/translate_batch_translate_text.test.js b/samples/test/v3/translate_batch_translate_text.test.js index ce831df6..bcb75b5c 100644 --- a/samples/test/v3/translate_batch_translate_text.test.js +++ b/samples/test/v3/translate_batch_translate_text.test.js @@ -51,7 +51,7 @@ describe(REGION_TAG, () => { it('should batch translate the input text', async () => { const projectId = await translationClient.getProjectId(); - const inputUri = `gs://cloud-samples-data/translation/text.txt`; + const inputUri = 'gs://cloud-samples-data/translation/text.txt'; const outputUri = `gs://${projectId}/${bucketName}`; const output = execSync( @@ -62,7 +62,7 @@ describe(REGION_TAG, () => { }); // Delete the folder from GCS for cleanup - after(async function() { + after(async () => { const projectId = await translationClient.getProjectId(); const options = { prefix: `translation-${bucketUuid}`, diff --git a/samples/test/v3/translate_batch_translate_text_with_glossary.test.js b/samples/test/v3/translate_batch_translate_text_with_glossary.test.js index e79458c6..1e15e6dc 100644 --- a/samples/test/v3/translate_batch_translate_text_with_glossary.test.js +++ b/samples/test/v3/translate_batch_translate_text_with_glossary.test.js @@ -73,7 +73,7 @@ describe(REGION_TAG, () => { it('should batch translate the input text with a glossary', async () => { const projectId = await translationClient.getProjectId(); - const inputUri = `gs://cloud-samples-data/translation/text.txt`; + const inputUri = 'gs://cloud-samples-data/translation/text.txt'; const outputUri = `gs://${projectId}/${bucketName}`; const output = execSync( @@ -84,7 +84,7 @@ describe(REGION_TAG, () => { }); // Delete the folder from GCS for cleanup - after(async function() { + after(async () => { const projectId = await translationClient.getProjectId(); const options = { prefix: `translation-${bucketUuid}`, diff --git a/samples/test/v3/translate_batch_translate_text_with_glossary_and_model.test.js b/samples/test/v3/translate_batch_translate_text_with_glossary_and_model.test.js index 74ecfcad..fb4d19ee 100644 --- a/samples/test/v3/translate_batch_translate_text_with_glossary_and_model.test.js +++ b/samples/test/v3/translate_batch_translate_text_with_glossary_and_model.test.js @@ -74,7 +74,8 @@ describe(REGION_TAG, () => { it('should batch translate the input text with a glossary', async () => { const projectId = await translationClient.getProjectId(); - const inputUri = `gs://cloud-samples-data/translation/text_with_custom_model_and_glossary.txt`; + const inputUri = + 'gs://cloud-samples-data/translation/text_with_custom_model_and_glossary.txt'; const outputUri = `gs://${projectId}/${bucketName}`; const output = execSync( @@ -85,7 +86,7 @@ describe(REGION_TAG, () => { }); // Delete the folder from GCS for cleanup - after(async function() { + after(async () => { const projectId = await translationClient.getProjectId(); const options = { prefix: `translation-${bucketUuid}`, diff --git a/samples/test/v3/translate_batch_translate_text_with_model.test.js b/samples/test/v3/translate_batch_translate_text_with_model.test.js index 91344ded..76113e4c 100644 --- a/samples/test/v3/translate_batch_translate_text_with_model.test.js +++ b/samples/test/v3/translate_batch_translate_text_with_model.test.js @@ -52,7 +52,8 @@ describe(REGION_TAG, () => { it('should batch translate the input text with a model', async () => { const projectId = await translationClient.getProjectId(); - const inputUri = `gs://cloud-samples-data/translation/custom_model_text.txt`; + const inputUri = + 'gs://cloud-samples-data/translation/custom_model_text.txt'; const outputUri = `gs://${projectId}/${bucketName}`; const output = execSync( @@ -63,7 +64,7 @@ describe(REGION_TAG, () => { }); // Delete the folder from GCS for cleanup - after(async function() { + after(async () => { const projectId = await translationClient.getProjectId(); const options = { prefix: `translation-${bucketUuid}`, diff --git a/samples/test/v3/translate_create_glossary.test.js b/samples/test/v3/translate_create_glossary.test.js index 4c69b4b1..c708de74 100644 --- a/samples/test/v3/translate_create_glossary.test.js +++ b/samples/test/v3/translate_create_glossary.test.js @@ -29,7 +29,7 @@ describe(REGION_TAG, () => { const glossaryId = `my_test_glossary_${uuid.v4()}`; const location = 'us-central1'; - it('should create a glossary', async function() { + it('should create a glossary', async () => { const projectId = await translationClient.getProjectId(); const output = execSync( `node v3/${REGION_TAG}.js ${projectId} ${location} ${glossaryId}` @@ -40,7 +40,7 @@ describe(REGION_TAG, () => { ); }); - after('cleanup for glossary create', async function() { + after('cleanup for glossary create', async () => { const projectId = await translationClient.getProjectId(); // Delete the glossary to clean up const request = { diff --git a/samples/test/v3/translate_delete_glossary.test.js b/samples/test/v3/translate_delete_glossary.test.js index dbb6551a..0a4b0450 100644 --- a/samples/test/v3/translate_delete_glossary.test.js +++ b/samples/test/v3/translate_delete_glossary.test.js @@ -29,7 +29,7 @@ describe(REGION_TAG, () => { const location = 'us-central1'; const glossaryId = `my_test_glossary_${uuid.v4()}`; - before(async function() { + before(async () => { // Add a glossary to be deleted // const translationClient = new TranslationServiceClient(); const projectId = await translationClient.getProjectId(); diff --git a/samples/test/v3/translate_detect_language.test.js b/samples/test/v3/translate_detect_language.test.js index eabf8268..ae0743e9 100644 --- a/samples/test/v3/translate_detect_language.test.js +++ b/samples/test/v3/translate_detect_language.test.js @@ -28,7 +28,7 @@ describe(REGION_TAG, () => { const translationClient = new TranslationServiceClient(); const projectId = await translationClient.getProjectId(); const location = 'global'; - const text = `'Hæ sæta'`; + const text = "'Hæ sæta'"; const output = execSync( `node v3/${REGION_TAG}.js ${projectId} ${location} ${text}` ); diff --git a/samples/test/v3/translate_get_glossary.test.js b/samples/test/v3/translate_get_glossary.test.js index 0fac5016..aad0f4fc 100644 --- a/samples/test/v3/translate_get_glossary.test.js +++ b/samples/test/v3/translate_get_glossary.test.js @@ -29,7 +29,7 @@ describe(REGION_TAG, () => { const location = 'us-central1'; const glossaryId = `my_test_glossary_${uuid.v4()}`; - before(async function() { + before(async () => { // Add a glossary to get const projectId = await translationClient.getProjectId(); const glossary = { @@ -67,7 +67,7 @@ describe(REGION_TAG, () => { assert.match(output, /my_test_glossary_/); }); - after(async function() { + after(async () => { //delete the glossary we created const projectId = await translationClient.getProjectId(); const request = { diff --git a/samples/test/v3/translate_list_glossary.test.js b/samples/test/v3/translate_list_glossary.test.js index 3ca68a2b..1ae9ac74 100644 --- a/samples/test/v3/translate_list_glossary.test.js +++ b/samples/test/v3/translate_list_glossary.test.js @@ -29,7 +29,7 @@ describe(REGION_TAG, () => { const location = 'us-central1'; const glossaryId = `my_test_glossary_${uuid.v4()}`; - before(async function() { + before(async () => { // Add a glossary to be deleted const projectId = await translationClient.getProjectId(); @@ -70,7 +70,7 @@ describe(REGION_TAG, () => { ); }); - after(async function() { + after(async () => { const projectId = await translationClient.getProjectId(); const request = { diff --git a/samples/test/v3/translate_translate_text.test.js b/samples/test/v3/translate_translate_text.test.js index 4393c085..4acba8d8 100644 --- a/samples/test/v3/translate_translate_text.test.js +++ b/samples/test/v3/translate_translate_text.test.js @@ -27,8 +27,8 @@ describe(REGION_TAG, () => { it('should translate the input text', async () => { const translationClient = new TranslationServiceClient(); const projectId = await translationClient.getProjectId(); - const location = `global`; - const text = `"Hello world"`; + const location = 'global'; + const text = '"Hello world"'; const output = execSync( `node v3/${REGION_TAG}.js ${projectId} ${location} ${text}` ); diff --git a/samples/test/v3/translate_translate_text_with_glossary.test.js b/samples/test/v3/translate_translate_text_with_glossary.test.js index 97cc5f78..1b9c8240 100644 --- a/samples/test/v3/translate_translate_text_with_glossary.test.js +++ b/samples/test/v3/translate_translate_text_with_glossary.test.js @@ -29,7 +29,7 @@ describe(REGION_TAG, () => { const location = 'us-central1'; const glossaryId = `my_test_glossary_${uuid.v4()}`; - before(async function() { + before(async () => { // Add a glossary to be translate with const projectId = await translationClient.getProjectId(); @@ -68,7 +68,7 @@ describe(REGION_TAG, () => { assert.match(output, /indicaciones/); }); - after(async function() { + after(async () => { const projectId = await translationClient.getProjectId(); const request = { parent: `projects/${projectId}/locations/${location}`, diff --git a/samples/test/v3/translate_translate_text_with_glossary_and_model.test.js b/samples/test/v3/translate_translate_text_with_glossary_and_model.test.js index 15d4615b..ed0cfb0d 100644 --- a/samples/test/v3/translate_translate_text_with_glossary_and_model.test.js +++ b/samples/test/v3/translate_translate_text_with_glossary_and_model.test.js @@ -30,7 +30,7 @@ describe(REGION_TAG, () => { const glossaryId = `my_test_glossary_${uuid.v4()}`; const modelId = 'TRL1218052175389786112'; - before(async function() { + before(async () => { // Add a glossary to be translate with const projectId = await translationClient.getProjectId(); @@ -69,7 +69,7 @@ describe(REGION_TAG, () => { assert.match(output, /道順/); }); - after(async function() { + after(async () => { const projectId = await translationClient.getProjectId(); const request = { parent: `projects/${projectId}/locations/${location}`, diff --git a/samples/test/v3beta1/translate_batch_translate_text_beta.test.js b/samples/test/v3beta1/translate_batch_translate_text_beta.test.js index 7a5ecef7..69614c30 100644 --- a/samples/test/v3beta1/translate_batch_translate_text_beta.test.js +++ b/samples/test/v3beta1/translate_batch_translate_text_beta.test.js @@ -51,7 +51,7 @@ describe(REGION_TAG, () => { it('should batch translate the input text', async () => { const projectId = await translationClient.getProjectId(); - const inputUri = `gs://cloud-samples-data/translation/text.txt`; + const inputUri = 'gs://cloud-samples-data/translation/text.txt'; const outputUri = `gs://${projectId}/${bucketName}`; const output = execSync( @@ -62,7 +62,7 @@ describe(REGION_TAG, () => { }); // Delete the folder from GCS for cleanup - after(async function() { + after(async () => { const projectId = await translationClient.getProjectId(); const options = { prefix: `translation-${bucketUuid}`, diff --git a/samples/test/v3beta1/translate_create_glossary_beta.test.js b/samples/test/v3beta1/translate_create_glossary_beta.test.js index 4ff2dcb2..46832a04 100644 --- a/samples/test/v3beta1/translate_create_glossary_beta.test.js +++ b/samples/test/v3beta1/translate_create_glossary_beta.test.js @@ -26,7 +26,7 @@ const REGION_TAG = 'translate_create_glossary_beta'; describe(REGION_TAG, () => { const translationClient = new TranslationServiceClient(); - it('should create a glossary', async function() { + it('should create a glossary', async () => { const projectId = await translationClient.getProjectId(); const location = 'us-central1'; const glossaryId = 'test-glossary'; @@ -39,7 +39,7 @@ describe(REGION_TAG, () => { ); }); - after('cleanup for glossary create', async function() { + after('cleanup for glossary create', async () => { const projectId = await translationClient.getProjectId(); const location = 'us-central1'; const glossaryId = 'test-glossary'; diff --git a/samples/test/v3beta1/translate_delete_glossary_beta.test.js b/samples/test/v3beta1/translate_delete_glossary_beta.test.js index 0653fc83..b3894872 100644 --- a/samples/test/v3beta1/translate_delete_glossary_beta.test.js +++ b/samples/test/v3beta1/translate_delete_glossary_beta.test.js @@ -28,7 +28,7 @@ describe(REGION_TAG, () => { const location = 'us-central1'; const glossaryId = 'glossary'; - before(async function() { + before(async () => { // Add a glossary to be deleted // const translationClient = new TranslationServiceClient(); const projectId = await translationClient.getProjectId(); diff --git a/samples/test/v3beta1/translate_detect_language_beta.test.js b/samples/test/v3beta1/translate_detect_language_beta.test.js index 7a6715d2..814446d4 100644 --- a/samples/test/v3beta1/translate_detect_language_beta.test.js +++ b/samples/test/v3beta1/translate_detect_language_beta.test.js @@ -28,7 +28,7 @@ describe(REGION_TAG, () => { const translationClient = new TranslationServiceClient(); const projectId = await translationClient.getProjectId(); const location = 'global'; - const text = `'Hæ sæta'`; + const text = "'Hæ sæta'"; const output = execSync( `node v3beta1/${REGION_TAG}.js ${projectId} ${location} ${text}` ); diff --git a/samples/test/v3beta1/translate_get_glossary_beta.test.js b/samples/test/v3beta1/translate_get_glossary_beta.test.js index 590e974e..c07a47c5 100644 --- a/samples/test/v3beta1/translate_get_glossary_beta.test.js +++ b/samples/test/v3beta1/translate_get_glossary_beta.test.js @@ -28,7 +28,7 @@ describe(REGION_TAG, () => { const location = 'us-central1'; const glossaryId = 'test-glossary'; - before(async function() { + before(async () => { // Add a glossary to get const projectId = await translationClient.getProjectId(); const glossary = { @@ -66,7 +66,7 @@ describe(REGION_TAG, () => { assert.match(output, /test-glossary/); }); - after(async function() { + after(async () => { //delete the glossary we created const projectId = await translationClient.getProjectId(); const name = translationClient.glossaryPath( diff --git a/samples/test/v3beta1/translate_list_glossary_beta.test.js b/samples/test/v3beta1/translate_list_glossary_beta.test.js index bbcdc409..3313e18e 100644 --- a/samples/test/v3beta1/translate_list_glossary_beta.test.js +++ b/samples/test/v3beta1/translate_list_glossary_beta.test.js @@ -28,7 +28,7 @@ describe(REGION_TAG, () => { const location = 'us-central1'; const glossaryId = 'test-glossary'; - before(async function() { + before(async () => { // Add a glossary to be deleted const projectId = await translationClient.getProjectId(); @@ -69,7 +69,7 @@ describe(REGION_TAG, () => { ); }); - after(async function() { + after(async () => { const projectId = await translationClient.getProjectId(); const name = translationClient.glossaryPath( projectId, diff --git a/samples/test/v3beta1/translate_translate_text_beta.test.js b/samples/test/v3beta1/translate_translate_text_beta.test.js index a6bde088..7ea78f16 100644 --- a/samples/test/v3beta1/translate_translate_text_beta.test.js +++ b/samples/test/v3beta1/translate_translate_text_beta.test.js @@ -27,8 +27,8 @@ describe(REGION_TAG, () => { it('should translate the input text', async () => { const translationClient = new TranslationServiceClient(); const projectId = await translationClient.getProjectId(); - const location = `global`; - const text = `"Hello world"`; + const location = 'global'; + const text = '"Hello world"'; const output = execSync( `node v3beta1/${REGION_TAG}.js ${projectId} ${location} ${text}` ); diff --git a/samples/test/v3beta1/translate_translate_text_with_glossary_beta.test.js b/samples/test/v3beta1/translate_translate_text_with_glossary_beta.test.js index a9992c62..0c3f44bf 100644 --- a/samples/test/v3beta1/translate_translate_text_with_glossary_beta.test.js +++ b/samples/test/v3beta1/translate_translate_text_with_glossary_beta.test.js @@ -28,7 +28,7 @@ describe(REGION_TAG, () => { const location = 'us-central1'; const glossaryId = 'test-glossary'; - before(async function() { + before(async () => { // Add a glossary to be translate with const projectId = await translationClient.getProjectId(); @@ -67,7 +67,7 @@ describe(REGION_TAG, () => { assert.match(output, /indicaciones/); }); - after(async function() { + after(async () => { const projectId = await translationClient.getProjectId(); const name = translationClient.glossaryPath( projectId, diff --git a/samples/translate.js b/samples/translate.js index c59bd514..e52db72d 100644 --- a/samples/translate.js +++ b/samples/translate.js @@ -157,17 +157,17 @@ function translateTextWithModelSample(text, target, model) { // [END translate_text_with_model] } -require(`yargs`) +require('yargs') .demand(1) .command( - `detect `, - `Detects the language of one or more strings.`, + 'detect ', + 'Detects the language of one or more strings.', {}, async opts => await detectLanguageSample(opts.text) ) .command( - `list [target]`, - `Lists available translation languages. To language names in a language other than English, specify a target language.`, + 'list [target]', + 'Lists available translation languages. To language names in a language other than English, specify a target language.', {}, async opts => { if (opts.target) { @@ -178,45 +178,45 @@ require(`yargs`) } ) .command( - `translate `, - `Translates one or more strings into the target language.`, + 'translate ', + 'Translates one or more strings into the target language.', {}, async opts => await translateTextSample(opts.text, opts.toLang) ) .command( - `translate-with-model `, - `Translates one or more strings into the target language using the specified model.`, + 'translate-with-model ', + 'Translates one or more strings into the target language using the specified model.', {}, async opts => await translateTextWithModelSample(opts.text, opts.toLang, opts.model) ) - .example(`node $0 detect "Hello world!"`, `Detects the language of a string.`) + .example('node $0 detect "Hello world!"', 'Detects the language of a string.') .example( - `node $0 detect "Hello world!" "Goodbye"`, - `Detects the languages of multiple strings.` + 'node $0 detect "Hello world!" "Goodbye"', + 'Detects the languages of multiple strings.' ) .example( - `node $0 list`, - `Lists available translation languages with names in English.` + 'node $0 list', + 'Lists available translation languages with names in English.' ) .example( - `node $0 list es`, - `Lists available translation languages with names in Spanish.` + 'node $0 list es', + 'Lists available translation languages with names in Spanish.' ) .example( - `node $0 translate ru "Good morning!"`, - `Translates a string into Russian.` + 'node $0 translate ru "Good morning!"', + 'Translates a string into Russian.' ) .example( - `node $0 translate ru "Good morning!" "Good night!"`, - `Translates multiple strings into Russian.` + 'node $0 translate ru "Good morning!" "Good night!"', + 'Translates multiple strings into Russian.' ) .example( - `node $0 translate-with-model ru nmt "Good morning!" "Good night!"`, - `Translates multiple strings into Russian using the Premium model.` + 'node $0 translate-with-model ru nmt "Good morning!" "Good night!"', + 'Translates multiple strings into Russian using the Premium model.' ) .wrap(120) .recommendCommands() - .epilogue(`For more information, see https://cloud.google.com/translate/docs`) + .epilogue('For more information, see https://cloud.google.com/translate/docs') .help() .strict().argv; diff --git a/samples/v3/translate_create_glossary.js b/samples/v3/translate_create_glossary.js index 666634d2..f59300a1 100644 --- a/samples/v3/translate_create_glossary.js +++ b/samples/v3/translate_create_glossary.js @@ -60,7 +60,7 @@ function main( // Wait for the operation to complete await operation.promise(); - console.log(`Created glossary:`); + console.log('Created glossary:'); console.log( `InputUri ${request.glossary.inputConfig.gcsSource.inputUri}` ); diff --git a/samples/v3/translate_detect_language.js b/samples/v3/translate_detect_language.js index 1e588ef8..e9877f6c 100644 --- a/samples/v3/translate_detect_language.js +++ b/samples/v3/translate_detect_language.js @@ -44,7 +44,7 @@ function main( // Run request const [response] = await translationClient.detectLanguage(request); - console.log(`Detected Languages:`); + console.log('Detected Languages:'); for (const language of response.languages) { console.log(`Language Code: ${language.languageCode}`); console.log(`Confidence: ${language.confidence}`); diff --git a/samples/v3/translate_list_codes.js b/samples/v3/translate_list_codes.js index 56fa1dc9..fe366fc9 100644 --- a/samples/v3/translate_list_codes.js +++ b/samples/v3/translate_list_codes.js @@ -38,7 +38,7 @@ function main(projectId = 'YOUR_PROJECT_ID', location = 'global') { // Run request const [response] = await translationClient.getSupportedLanguages(request); - console.log(`Supported languages:`); + console.log('Supported languages:'); for (const language of response.languages) { console.log(`Language Code: ${language.languageCode}`); } diff --git a/samples/v3/translate_list_language_names.js b/samples/v3/translate_list_language_names.js index 3ea6f7d2..763429a6 100644 --- a/samples/v3/translate_list_language_names.js +++ b/samples/v3/translate_list_language_names.js @@ -39,7 +39,7 @@ function main(projectId = 'YOUR_PROJECT_ID', location = 'global') { // Run request const [response] = await translationClient.getSupportedLanguages(request); - console.log(`Supported languages:`); + console.log('Supported languages:'); for (const language of response.languages) { console.log(`Language Code: ${language.languageCode}`); console.log(`Display Name: ${language.displayName}`); diff --git a/samples/v3beta1/translate_create_glossary_beta.js b/samples/v3beta1/translate_create_glossary_beta.js index 1e522059..5b50459f 100644 --- a/samples/v3beta1/translate_create_glossary_beta.js +++ b/samples/v3beta1/translate_create_glossary_beta.js @@ -59,7 +59,7 @@ function main( // Wait for operation to complete. await operation.promise(); - console.log(`Created glossary:`); + console.log('Created glossary:'); console.log(`InputUri ${request.glossary.inputConfig.gcsSource.inputUri}`); } diff --git a/samples/v3beta1/translate_detect_language_beta.js b/samples/v3beta1/translate_detect_language_beta.js index a165e85e..1746eb57 100644 --- a/samples/v3beta1/translate_detect_language_beta.js +++ b/samples/v3beta1/translate_detect_language_beta.js @@ -42,7 +42,7 @@ function main( // Run request const [response] = await translationClient.detectLanguage(request); - console.log(`Detected Languages:`); + console.log('Detected Languages:'); for (const language of response.languages) { console.log(`Language Code: ${language.languageCode}`); console.log(`Confidence: ${language.confidence}`); diff --git a/samples/v3beta1/translate_list_codes_beta.js b/samples/v3beta1/translate_list_codes_beta.js index eb96819b..f67c1d34 100644 --- a/samples/v3beta1/translate_list_codes_beta.js +++ b/samples/v3beta1/translate_list_codes_beta.js @@ -37,7 +37,7 @@ function main(projectId = 'YOUR_PROJECT_ID', location = 'global') { // Run request const [response] = await translationClient.getSupportedLanguages(request); - console.log(`Supported languages:`); + console.log('Supported languages:'); for (const language of response.languages) { console.log(`Language Code: ${language.languageCode}`); } diff --git a/samples/v3beta1/translate_list_language_names_beta.js b/samples/v3beta1/translate_list_language_names_beta.js index 80e4fa57..4fe0103b 100644 --- a/samples/v3beta1/translate_list_language_names_beta.js +++ b/samples/v3beta1/translate_list_language_names_beta.js @@ -38,7 +38,7 @@ function main(projectId = 'YOUR_PROJECT_ID', location = 'global') { // Run request const [response] = await translationClient.getSupportedLanguages(request); - console.log(`Supported languages:`); + console.log('Supported languages:'); for (const language of response.languages) { console.log(`Language Code: ${language.languageCode}`); console.log(`Display Name: ${language.displayName}`); diff --git a/src/v2/index.ts b/src/v2/index.ts index 4b6a2e92..76daff2c 100644 --- a/src/v2/index.ts +++ b/src/v2/index.ts @@ -18,12 +18,14 @@ import arrify = require('arrify'); import * as extend from 'extend'; import {GoogleAuthOptions} from 'google-auth-library'; +// eslint-disable-next-line @typescript-eslint/no-var-requires const isHtml = require('is-html'); import { DecorateRequestOptions, BodyResponseCallback, } from '@google-cloud/common/build/src/util'; +// eslint-disable-next-line @typescript-eslint/no-var-requires const PKG = require('../../../package.json'); export interface TranslateRequest { diff --git a/src/v3/translation_service_client.ts b/src/v3/translation_service_client.ts index 052a5fa3..0acb7f8f 100644 --- a/src/v3/translation_service_client.ts +++ b/src/v3/translation_service_client.ts @@ -18,19 +18,19 @@ import * as gax from 'google-gax'; import { - APICallback, Callback, CallOptions, Descriptors, ClientOptions, LROperation, PaginationCallback, - PaginationResponse, + GaxCall, } from 'google-gax'; import * as path from 'path'; import {Transform} from 'stream'; -import * as protosTypes from '../../protos/protos'; +import {RequestType} from 'google-gax/build/src/apitypes'; +import * as protos from '../../protos/protos'; import * as gapicConfig from './translation_service_client_config.json'; const version = require('../../../package.json').version; @@ -41,14 +41,6 @@ const version = require('../../../package.json').version; * @memberof v3 */ export class TranslationServiceClient { - private _descriptors: Descriptors = { - page: {}, - stream: {}, - longrunning: {}, - batching: {}, - }; - private _innerApiCalls: {[name: string]: Function}; - private _pathTemplates: {[name: string]: gax.PathTemplate}; private _terminated = false; private _opts: ClientOptions; private _gaxModule: typeof gax | typeof gax.fallback; @@ -56,6 +48,14 @@ export class TranslationServiceClient { private _protos: {}; private _defaults: {[method: string]: gax.CallSettings}; auth: gax.GoogleAuth; + descriptors: Descriptors = { + page: {}, + stream: {}, + longrunning: {}, + batching: {}, + }; + innerApiCalls: {[name: string]: Function}; + pathTemplates: {[name: string]: gax.PathTemplate}; operationsClient: gax.OperationsClient; translationServiceStub?: Promise<{[name: string]: Function}>; @@ -148,13 +148,16 @@ export class TranslationServiceClient { 'protos.json' ); this._protos = this._gaxGrpc.loadProto( - opts.fallback ? require('../../protos/protos.json') : nodejsProtoPath + opts.fallback + ? // eslint-disable-next-line @typescript-eslint/no-var-requires + require('../../protos/protos.json') + : nodejsProtoPath ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. - this._pathTemplates = { + this.pathTemplates = { glossaryPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/locations/{location}/glossaries/{glossary}' ), @@ -166,7 +169,7 @@ export class TranslationServiceClient { // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. - this._descriptors.page = { + this.descriptors.page = { listGlossaries: new this._gaxModule.PageDescriptor( 'pageToken', 'nextPageToken', @@ -179,6 +182,7 @@ export class TranslationServiceClient { // rather than holding a request open. const protoFilesRoot = opts.fallback ? this._gaxModule.protobuf.Root.fromJSON( + // eslint-disable-next-line @typescript-eslint/no-var-requires require('../../protos/protos.json') ) : this._gaxModule.protobuf.loadSync(nodejsProtoPath); @@ -208,7 +212,7 @@ export class TranslationServiceClient { '.google.cloud.translation.v3.DeleteGlossaryMetadata' ) as gax.protobuf.Type; - this._descriptors.longrunning = { + this.descriptors.longrunning = { batchTranslateText: new this._gaxModule.LongrunningDescriptor( this.operationsClient, batchTranslateTextResponse.decode.bind(batchTranslateTextResponse), @@ -237,7 +241,7 @@ export class TranslationServiceClient { // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code // merely providing the destination and request information. - this._innerApiCalls = {}; + this.innerApiCalls = {}; } /** @@ -264,7 +268,7 @@ export class TranslationServiceClient { ? (this._protos as protobuf.Root).lookupService( 'google.cloud.translation.v3.TranslationService' ) - : // tslint:disable-next-line no-any + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.translation.v3.TranslationService, this._opts ) as Promise<{[method: string]: Function}>; @@ -281,9 +285,8 @@ export class TranslationServiceClient { 'getGlossary', 'deleteGlossary', ]; - for (const methodName of translationServiceStubMethods) { - const innerCallPromise = this.translationServiceStub.then( + const callPromise = this.translationServiceStub.then( stub => (...args: Array<{}>) => { if (this._terminated) { return Promise.reject('The client has already been closed.'); @@ -297,20 +300,14 @@ export class TranslationServiceClient { ); const apiCall = this._gaxModule.createApiCall( - innerCallPromise, + callPromise, this._defaults[methodName], - this._descriptors.page[methodName] || - this._descriptors.stream[methodName] || - this._descriptors.longrunning[methodName] + this.descriptors.page[methodName] || + this.descriptors.stream[methodName] || + this.descriptors.longrunning[methodName] ); - this._innerApiCalls[methodName] = ( - argument: {}, - callOptions?: CallOptions, - callback?: APICallback - ) => { - return apiCall(argument, callOptions, callback); - }; + this.innerApiCalls[methodName] = apiCall; } return this.translationServiceStub; @@ -370,22 +367,34 @@ export class TranslationServiceClient { // -- Service calls -- // ------------------- translateText( - request: protosTypes.google.cloud.translation.v3.ITranslateTextRequest, + request: protos.google.cloud.translation.v3.ITranslateTextRequest, options?: gax.CallOptions ): Promise< [ - protosTypes.google.cloud.translation.v3.ITranslateTextResponse, - protosTypes.google.cloud.translation.v3.ITranslateTextRequest | undefined, + protos.google.cloud.translation.v3.ITranslateTextResponse, + protos.google.cloud.translation.v3.ITranslateTextRequest | undefined, {} | undefined ] >; translateText( - request: protosTypes.google.cloud.translation.v3.ITranslateTextRequest, + request: protos.google.cloud.translation.v3.ITranslateTextRequest, options: gax.CallOptions, callback: Callback< - protosTypes.google.cloud.translation.v3.ITranslateTextResponse, - protosTypes.google.cloud.translation.v3.ITranslateTextRequest | undefined, - {} | undefined + protos.google.cloud.translation.v3.ITranslateTextResponse, + | protos.google.cloud.translation.v3.ITranslateTextRequest + | null + | undefined, + {} | null | undefined + > + ): void; + translateText( + request: protos.google.cloud.translation.v3.ITranslateTextRequest, + callback: Callback< + protos.google.cloud.translation.v3.ITranslateTextResponse, + | protos.google.cloud.translation.v3.ITranslateTextRequest + | null + | undefined, + {} | null | undefined > ): void; /** @@ -462,24 +471,27 @@ export class TranslationServiceClient { * The promise has a method named "cancel" which cancels the ongoing API call. */ translateText( - request: protosTypes.google.cloud.translation.v3.ITranslateTextRequest, + request: protos.google.cloud.translation.v3.ITranslateTextRequest, optionsOrCallback?: | gax.CallOptions | Callback< - protosTypes.google.cloud.translation.v3.ITranslateTextResponse, - | protosTypes.google.cloud.translation.v3.ITranslateTextRequest + protos.google.cloud.translation.v3.ITranslateTextResponse, + | protos.google.cloud.translation.v3.ITranslateTextRequest + | null | undefined, - {} | undefined + {} | null | undefined >, callback?: Callback< - protosTypes.google.cloud.translation.v3.ITranslateTextResponse, - protosTypes.google.cloud.translation.v3.ITranslateTextRequest | undefined, - {} | undefined + protos.google.cloud.translation.v3.ITranslateTextResponse, + | protos.google.cloud.translation.v3.ITranslateTextRequest + | null + | undefined, + {} | null | undefined > ): Promise< [ - protosTypes.google.cloud.translation.v3.ITranslateTextResponse, - protosTypes.google.cloud.translation.v3.ITranslateTextRequest | undefined, + protos.google.cloud.translation.v3.ITranslateTextResponse, + protos.google.cloud.translation.v3.ITranslateTextRequest | undefined, {} | undefined ] > | void { @@ -500,29 +512,37 @@ export class TranslationServiceClient { parent: request.parent || '', }); this.initialize(); - return this._innerApiCalls.translateText(request, options, callback); + return this.innerApiCalls.translateText(request, options, callback); } detectLanguage( - request: protosTypes.google.cloud.translation.v3.IDetectLanguageRequest, + request: protos.google.cloud.translation.v3.IDetectLanguageRequest, options?: gax.CallOptions ): Promise< [ - protosTypes.google.cloud.translation.v3.IDetectLanguageResponse, - ( - | protosTypes.google.cloud.translation.v3.IDetectLanguageRequest - | undefined - ), + protos.google.cloud.translation.v3.IDetectLanguageResponse, + protos.google.cloud.translation.v3.IDetectLanguageRequest | undefined, {} | undefined ] >; detectLanguage( - request: protosTypes.google.cloud.translation.v3.IDetectLanguageRequest, + request: protos.google.cloud.translation.v3.IDetectLanguageRequest, options: gax.CallOptions, callback: Callback< - protosTypes.google.cloud.translation.v3.IDetectLanguageResponse, - | protosTypes.google.cloud.translation.v3.IDetectLanguageRequest + protos.google.cloud.translation.v3.IDetectLanguageResponse, + | protos.google.cloud.translation.v3.IDetectLanguageRequest + | null | undefined, - {} | undefined + {} | null | undefined + > + ): void; + detectLanguage( + request: protos.google.cloud.translation.v3.IDetectLanguageRequest, + callback: Callback< + protos.google.cloud.translation.v3.IDetectLanguageResponse, + | protos.google.cloud.translation.v3.IDetectLanguageRequest + | null + | undefined, + {} | null | undefined > ): void; /** @@ -573,28 +593,27 @@ export class TranslationServiceClient { * The promise has a method named "cancel" which cancels the ongoing API call. */ detectLanguage( - request: protosTypes.google.cloud.translation.v3.IDetectLanguageRequest, + request: protos.google.cloud.translation.v3.IDetectLanguageRequest, optionsOrCallback?: | gax.CallOptions | Callback< - protosTypes.google.cloud.translation.v3.IDetectLanguageResponse, - | protosTypes.google.cloud.translation.v3.IDetectLanguageRequest + protos.google.cloud.translation.v3.IDetectLanguageResponse, + | protos.google.cloud.translation.v3.IDetectLanguageRequest + | null | undefined, - {} | undefined + {} | null | undefined >, callback?: Callback< - protosTypes.google.cloud.translation.v3.IDetectLanguageResponse, - | protosTypes.google.cloud.translation.v3.IDetectLanguageRequest + protos.google.cloud.translation.v3.IDetectLanguageResponse, + | protos.google.cloud.translation.v3.IDetectLanguageRequest + | null | undefined, - {} | undefined + {} | null | undefined > ): Promise< [ - protosTypes.google.cloud.translation.v3.IDetectLanguageResponse, - ( - | protosTypes.google.cloud.translation.v3.IDetectLanguageRequest - | undefined - ), + protos.google.cloud.translation.v3.IDetectLanguageResponse, + protos.google.cloud.translation.v3.IDetectLanguageRequest | undefined, {} | undefined ] > | void { @@ -615,29 +634,40 @@ export class TranslationServiceClient { parent: request.parent || '', }); this.initialize(); - return this._innerApiCalls.detectLanguage(request, options, callback); + return this.innerApiCalls.detectLanguage(request, options, callback); } getSupportedLanguages( - request: protosTypes.google.cloud.translation.v3.IGetSupportedLanguagesRequest, + request: protos.google.cloud.translation.v3.IGetSupportedLanguagesRequest, options?: gax.CallOptions ): Promise< [ - protosTypes.google.cloud.translation.v3.ISupportedLanguages, + protos.google.cloud.translation.v3.ISupportedLanguages, ( - | protosTypes.google.cloud.translation.v3.IGetSupportedLanguagesRequest + | protos.google.cloud.translation.v3.IGetSupportedLanguagesRequest | undefined ), {} | undefined ] >; getSupportedLanguages( - request: protosTypes.google.cloud.translation.v3.IGetSupportedLanguagesRequest, + request: protos.google.cloud.translation.v3.IGetSupportedLanguagesRequest, options: gax.CallOptions, callback: Callback< - protosTypes.google.cloud.translation.v3.ISupportedLanguages, - | protosTypes.google.cloud.translation.v3.IGetSupportedLanguagesRequest + protos.google.cloud.translation.v3.ISupportedLanguages, + | protos.google.cloud.translation.v3.IGetSupportedLanguagesRequest + | null | undefined, - {} | undefined + {} | null | undefined + > + ): void; + getSupportedLanguages( + request: protos.google.cloud.translation.v3.IGetSupportedLanguagesRequest, + callback: Callback< + protos.google.cloud.translation.v3.ISupportedLanguages, + | protos.google.cloud.translation.v3.IGetSupportedLanguagesRequest + | null + | undefined, + {} | null | undefined > ): void; /** @@ -685,26 +715,28 @@ export class TranslationServiceClient { * The promise has a method named "cancel" which cancels the ongoing API call. */ getSupportedLanguages( - request: protosTypes.google.cloud.translation.v3.IGetSupportedLanguagesRequest, + request: protos.google.cloud.translation.v3.IGetSupportedLanguagesRequest, optionsOrCallback?: | gax.CallOptions | Callback< - protosTypes.google.cloud.translation.v3.ISupportedLanguages, - | protosTypes.google.cloud.translation.v3.IGetSupportedLanguagesRequest + protos.google.cloud.translation.v3.ISupportedLanguages, + | protos.google.cloud.translation.v3.IGetSupportedLanguagesRequest + | null | undefined, - {} | undefined + {} | null | undefined >, callback?: Callback< - protosTypes.google.cloud.translation.v3.ISupportedLanguages, - | protosTypes.google.cloud.translation.v3.IGetSupportedLanguagesRequest + protos.google.cloud.translation.v3.ISupportedLanguages, + | protos.google.cloud.translation.v3.IGetSupportedLanguagesRequest + | null | undefined, - {} | undefined + {} | null | undefined > ): Promise< [ - protosTypes.google.cloud.translation.v3.ISupportedLanguages, + protos.google.cloud.translation.v3.ISupportedLanguages, ( - | protosTypes.google.cloud.translation.v3.IGetSupportedLanguagesRequest + | protos.google.cloud.translation.v3.IGetSupportedLanguagesRequest | undefined ), {} | undefined @@ -727,29 +759,33 @@ export class TranslationServiceClient { parent: request.parent || '', }); this.initialize(); - return this._innerApiCalls.getSupportedLanguages( - request, - options, - callback - ); + return this.innerApiCalls.getSupportedLanguages(request, options, callback); } getGlossary( - request: protosTypes.google.cloud.translation.v3.IGetGlossaryRequest, + request: protos.google.cloud.translation.v3.IGetGlossaryRequest, options?: gax.CallOptions ): Promise< [ - protosTypes.google.cloud.translation.v3.IGlossary, - protosTypes.google.cloud.translation.v3.IGetGlossaryRequest | undefined, + protos.google.cloud.translation.v3.IGlossary, + protos.google.cloud.translation.v3.IGetGlossaryRequest | undefined, {} | undefined ] >; getGlossary( - request: protosTypes.google.cloud.translation.v3.IGetGlossaryRequest, + request: protos.google.cloud.translation.v3.IGetGlossaryRequest, options: gax.CallOptions, callback: Callback< - protosTypes.google.cloud.translation.v3.IGlossary, - protosTypes.google.cloud.translation.v3.IGetGlossaryRequest | undefined, - {} | undefined + protos.google.cloud.translation.v3.IGlossary, + protos.google.cloud.translation.v3.IGetGlossaryRequest | null | undefined, + {} | null | undefined + > + ): void; + getGlossary( + request: protos.google.cloud.translation.v3.IGetGlossaryRequest, + callback: Callback< + protos.google.cloud.translation.v3.IGlossary, + protos.google.cloud.translation.v3.IGetGlossaryRequest | null | undefined, + {} | null | undefined > ): void; /** @@ -767,24 +803,25 @@ export class TranslationServiceClient { * The promise has a method named "cancel" which cancels the ongoing API call. */ getGlossary( - request: protosTypes.google.cloud.translation.v3.IGetGlossaryRequest, + request: protos.google.cloud.translation.v3.IGetGlossaryRequest, optionsOrCallback?: | gax.CallOptions | Callback< - protosTypes.google.cloud.translation.v3.IGlossary, - | protosTypes.google.cloud.translation.v3.IGetGlossaryRequest + protos.google.cloud.translation.v3.IGlossary, + | protos.google.cloud.translation.v3.IGetGlossaryRequest + | null | undefined, - {} | undefined + {} | null | undefined >, callback?: Callback< - protosTypes.google.cloud.translation.v3.IGlossary, - protosTypes.google.cloud.translation.v3.IGetGlossaryRequest | undefined, - {} | undefined + protos.google.cloud.translation.v3.IGlossary, + protos.google.cloud.translation.v3.IGetGlossaryRequest | null | undefined, + {} | null | undefined > ): Promise< [ - protosTypes.google.cloud.translation.v3.IGlossary, - protosTypes.google.cloud.translation.v3.IGetGlossaryRequest | undefined, + protos.google.cloud.translation.v3.IGlossary, + protos.google.cloud.translation.v3.IGetGlossaryRequest | undefined, {} | undefined ] > | void { @@ -805,32 +842,43 @@ export class TranslationServiceClient { name: request.name || '', }); this.initialize(); - return this._innerApiCalls.getGlossary(request, options, callback); + return this.innerApiCalls.getGlossary(request, options, callback); } batchTranslateText( - request: protosTypes.google.cloud.translation.v3.IBatchTranslateTextRequest, + request: protos.google.cloud.translation.v3.IBatchTranslateTextRequest, options?: gax.CallOptions ): Promise< [ LROperation< - protosTypes.google.cloud.translation.v3.IBatchTranslateResponse, - protosTypes.google.cloud.translation.v3.IBatchTranslateMetadata + protos.google.cloud.translation.v3.IBatchTranslateResponse, + protos.google.cloud.translation.v3.IBatchTranslateMetadata >, - protosTypes.google.longrunning.IOperation | undefined, + protos.google.longrunning.IOperation | undefined, {} | undefined ] >; batchTranslateText( - request: protosTypes.google.cloud.translation.v3.IBatchTranslateTextRequest, + request: protos.google.cloud.translation.v3.IBatchTranslateTextRequest, options: gax.CallOptions, callback: Callback< LROperation< - protosTypes.google.cloud.translation.v3.IBatchTranslateResponse, - protosTypes.google.cloud.translation.v3.IBatchTranslateMetadata + protos.google.cloud.translation.v3.IBatchTranslateResponse, + protos.google.cloud.translation.v3.IBatchTranslateMetadata >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + batchTranslateText( + request: protos.google.cloud.translation.v3.IBatchTranslateTextRequest, + callback: Callback< + LROperation< + protos.google.cloud.translation.v3.IBatchTranslateResponse, + protos.google.cloud.translation.v3.IBatchTranslateMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined > ): void; /** @@ -903,32 +951,32 @@ export class TranslationServiceClient { * The promise has a method named "cancel" which cancels the ongoing API call. */ batchTranslateText( - request: protosTypes.google.cloud.translation.v3.IBatchTranslateTextRequest, + request: protos.google.cloud.translation.v3.IBatchTranslateTextRequest, optionsOrCallback?: | gax.CallOptions | Callback< LROperation< - protosTypes.google.cloud.translation.v3.IBatchTranslateResponse, - protosTypes.google.cloud.translation.v3.IBatchTranslateMetadata + protos.google.cloud.translation.v3.IBatchTranslateResponse, + protos.google.cloud.translation.v3.IBatchTranslateMetadata >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined >, callback?: Callback< LROperation< - protosTypes.google.cloud.translation.v3.IBatchTranslateResponse, - protosTypes.google.cloud.translation.v3.IBatchTranslateMetadata + protos.google.cloud.translation.v3.IBatchTranslateResponse, + protos.google.cloud.translation.v3.IBatchTranslateMetadata >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined > ): Promise< [ LROperation< - protosTypes.google.cloud.translation.v3.IBatchTranslateResponse, - protosTypes.google.cloud.translation.v3.IBatchTranslateMetadata + protos.google.cloud.translation.v3.IBatchTranslateResponse, + protos.google.cloud.translation.v3.IBatchTranslateMetadata >, - protosTypes.google.longrunning.IOperation | undefined, + protos.google.longrunning.IOperation | undefined, {} | undefined ] > | void { @@ -949,31 +997,42 @@ export class TranslationServiceClient { parent: request.parent || '', }); this.initialize(); - return this._innerApiCalls.batchTranslateText(request, options, callback); + return this.innerApiCalls.batchTranslateText(request, options, callback); } createGlossary( - request: protosTypes.google.cloud.translation.v3.ICreateGlossaryRequest, + request: protos.google.cloud.translation.v3.ICreateGlossaryRequest, options?: gax.CallOptions ): Promise< [ LROperation< - protosTypes.google.cloud.translation.v3.IGlossary, - protosTypes.google.cloud.translation.v3.ICreateGlossaryMetadata + protos.google.cloud.translation.v3.IGlossary, + protos.google.cloud.translation.v3.ICreateGlossaryMetadata >, - protosTypes.google.longrunning.IOperation | undefined, + protos.google.longrunning.IOperation | undefined, {} | undefined ] >; createGlossary( - request: protosTypes.google.cloud.translation.v3.ICreateGlossaryRequest, + request: protos.google.cloud.translation.v3.ICreateGlossaryRequest, options: gax.CallOptions, callback: Callback< LROperation< - protosTypes.google.cloud.translation.v3.IGlossary, - protosTypes.google.cloud.translation.v3.ICreateGlossaryMetadata + protos.google.cloud.translation.v3.IGlossary, + protos.google.cloud.translation.v3.ICreateGlossaryMetadata >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + createGlossary( + request: protos.google.cloud.translation.v3.ICreateGlossaryRequest, + callback: Callback< + LROperation< + protos.google.cloud.translation.v3.IGlossary, + protos.google.cloud.translation.v3.ICreateGlossaryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined > ): void; /** @@ -993,32 +1052,32 @@ export class TranslationServiceClient { * The promise has a method named "cancel" which cancels the ongoing API call. */ createGlossary( - request: protosTypes.google.cloud.translation.v3.ICreateGlossaryRequest, + request: protos.google.cloud.translation.v3.ICreateGlossaryRequest, optionsOrCallback?: | gax.CallOptions | Callback< LROperation< - protosTypes.google.cloud.translation.v3.IGlossary, - protosTypes.google.cloud.translation.v3.ICreateGlossaryMetadata + protos.google.cloud.translation.v3.IGlossary, + protos.google.cloud.translation.v3.ICreateGlossaryMetadata >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined >, callback?: Callback< LROperation< - protosTypes.google.cloud.translation.v3.IGlossary, - protosTypes.google.cloud.translation.v3.ICreateGlossaryMetadata + protos.google.cloud.translation.v3.IGlossary, + protos.google.cloud.translation.v3.ICreateGlossaryMetadata >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined > ): Promise< [ LROperation< - protosTypes.google.cloud.translation.v3.IGlossary, - protosTypes.google.cloud.translation.v3.ICreateGlossaryMetadata + protos.google.cloud.translation.v3.IGlossary, + protos.google.cloud.translation.v3.ICreateGlossaryMetadata >, - protosTypes.google.longrunning.IOperation | undefined, + protos.google.longrunning.IOperation | undefined, {} | undefined ] > | void { @@ -1039,31 +1098,42 @@ export class TranslationServiceClient { parent: request.parent || '', }); this.initialize(); - return this._innerApiCalls.createGlossary(request, options, callback); + return this.innerApiCalls.createGlossary(request, options, callback); } deleteGlossary( - request: protosTypes.google.cloud.translation.v3.IDeleteGlossaryRequest, + request: protos.google.cloud.translation.v3.IDeleteGlossaryRequest, options?: gax.CallOptions ): Promise< [ LROperation< - protosTypes.google.cloud.translation.v3.IDeleteGlossaryResponse, - protosTypes.google.cloud.translation.v3.IDeleteGlossaryMetadata + protos.google.cloud.translation.v3.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3.IDeleteGlossaryMetadata >, - protosTypes.google.longrunning.IOperation | undefined, + protos.google.longrunning.IOperation | undefined, {} | undefined ] >; deleteGlossary( - request: protosTypes.google.cloud.translation.v3.IDeleteGlossaryRequest, + request: protos.google.cloud.translation.v3.IDeleteGlossaryRequest, options: gax.CallOptions, callback: Callback< LROperation< - protosTypes.google.cloud.translation.v3.IDeleteGlossaryResponse, - protosTypes.google.cloud.translation.v3.IDeleteGlossaryMetadata + protos.google.cloud.translation.v3.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3.IDeleteGlossaryMetadata >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + deleteGlossary( + request: protos.google.cloud.translation.v3.IDeleteGlossaryRequest, + callback: Callback< + LROperation< + protos.google.cloud.translation.v3.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3.IDeleteGlossaryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined > ): void; /** @@ -1082,32 +1152,32 @@ export class TranslationServiceClient { * The promise has a method named "cancel" which cancels the ongoing API call. */ deleteGlossary( - request: protosTypes.google.cloud.translation.v3.IDeleteGlossaryRequest, + request: protos.google.cloud.translation.v3.IDeleteGlossaryRequest, optionsOrCallback?: | gax.CallOptions | Callback< LROperation< - protosTypes.google.cloud.translation.v3.IDeleteGlossaryResponse, - protosTypes.google.cloud.translation.v3.IDeleteGlossaryMetadata + protos.google.cloud.translation.v3.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3.IDeleteGlossaryMetadata >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined >, callback?: Callback< LROperation< - protosTypes.google.cloud.translation.v3.IDeleteGlossaryResponse, - protosTypes.google.cloud.translation.v3.IDeleteGlossaryMetadata + protos.google.cloud.translation.v3.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3.IDeleteGlossaryMetadata >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined > ): Promise< [ LROperation< - protosTypes.google.cloud.translation.v3.IDeleteGlossaryResponse, - protosTypes.google.cloud.translation.v3.IDeleteGlossaryMetadata + protos.google.cloud.translation.v3.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3.IDeleteGlossaryMetadata >, - protosTypes.google.longrunning.IOperation | undefined, + protos.google.longrunning.IOperation | undefined, {} | undefined ] > | void { @@ -1128,25 +1198,37 @@ export class TranslationServiceClient { name: request.name || '', }); this.initialize(); - return this._innerApiCalls.deleteGlossary(request, options, callback); + return this.innerApiCalls.deleteGlossary(request, options, callback); } listGlossaries( - request: protosTypes.google.cloud.translation.v3.IListGlossariesRequest, + request: protos.google.cloud.translation.v3.IListGlossariesRequest, options?: gax.CallOptions ): Promise< [ - protosTypes.google.cloud.translation.v3.IGlossary[], - protosTypes.google.cloud.translation.v3.IListGlossariesRequest | null, - protosTypes.google.cloud.translation.v3.IListGlossariesResponse + protos.google.cloud.translation.v3.IGlossary[], + protos.google.cloud.translation.v3.IListGlossariesRequest | null, + protos.google.cloud.translation.v3.IListGlossariesResponse ] >; listGlossaries( - request: protosTypes.google.cloud.translation.v3.IListGlossariesRequest, + request: protos.google.cloud.translation.v3.IListGlossariesRequest, options: gax.CallOptions, - callback: Callback< - protosTypes.google.cloud.translation.v3.IGlossary[], - protosTypes.google.cloud.translation.v3.IListGlossariesRequest | null, - protosTypes.google.cloud.translation.v3.IListGlossariesResponse + callback: PaginationCallback< + protos.google.cloud.translation.v3.IListGlossariesRequest, + | protos.google.cloud.translation.v3.IListGlossariesResponse + | null + | undefined, + protos.google.cloud.translation.v3.IGlossary + > + ): void; + listGlossaries( + request: protos.google.cloud.translation.v3.IListGlossariesRequest, + callback: PaginationCallback< + protos.google.cloud.translation.v3.IListGlossariesRequest, + | protos.google.cloud.translation.v3.IListGlossariesResponse + | null + | undefined, + protos.google.cloud.translation.v3.IGlossary > ): void; /** @@ -1188,24 +1270,28 @@ export class TranslationServiceClient { * The promise has a method named "cancel" which cancels the ongoing API call. */ listGlossaries( - request: protosTypes.google.cloud.translation.v3.IListGlossariesRequest, + request: protos.google.cloud.translation.v3.IListGlossariesRequest, optionsOrCallback?: | gax.CallOptions - | Callback< - protosTypes.google.cloud.translation.v3.IGlossary[], - protosTypes.google.cloud.translation.v3.IListGlossariesRequest | null, - protosTypes.google.cloud.translation.v3.IListGlossariesResponse + | PaginationCallback< + protos.google.cloud.translation.v3.IListGlossariesRequest, + | protos.google.cloud.translation.v3.IListGlossariesResponse + | null + | undefined, + protos.google.cloud.translation.v3.IGlossary >, - callback?: Callback< - protosTypes.google.cloud.translation.v3.IGlossary[], - protosTypes.google.cloud.translation.v3.IListGlossariesRequest | null, - protosTypes.google.cloud.translation.v3.IListGlossariesResponse + callback?: PaginationCallback< + protos.google.cloud.translation.v3.IListGlossariesRequest, + | protos.google.cloud.translation.v3.IListGlossariesResponse + | null + | undefined, + protos.google.cloud.translation.v3.IGlossary > ): Promise< [ - protosTypes.google.cloud.translation.v3.IGlossary[], - protosTypes.google.cloud.translation.v3.IListGlossariesRequest | null, - protosTypes.google.cloud.translation.v3.IListGlossariesResponse + protos.google.cloud.translation.v3.IGlossary[], + protos.google.cloud.translation.v3.IListGlossariesRequest | null, + protos.google.cloud.translation.v3.IListGlossariesResponse ] > | void { request = request || {}; @@ -1225,7 +1311,7 @@ export class TranslationServiceClient { parent: request.parent || '', }); this.initialize(); - return this._innerApiCalls.listGlossaries(request, options, callback); + return this.innerApiCalls.listGlossaries(request, options, callback); } /** @@ -1263,7 +1349,7 @@ export class TranslationServiceClient { * An object stream which emits an object representing [Glossary]{@link google.cloud.translation.v3.Glossary} on 'data' event. */ listGlossariesStream( - request?: protosTypes.google.cloud.translation.v3.IListGlossariesRequest, + request?: protos.google.cloud.translation.v3.IListGlossariesRequest, options?: gax.CallOptions ): Transform { request = request || {}; @@ -1277,12 +1363,61 @@ export class TranslationServiceClient { }); const callSettings = new gax.CallSettings(options); this.initialize(); - return this._descriptors.page.listGlossaries.createStream( - this._innerApiCalls.listGlossaries as gax.GaxCall, + return this.descriptors.page.listGlossaries.createStream( + this.innerApiCalls.listGlossaries as gax.GaxCall, request, callSettings ); } + + /** + * Equivalent to {@link listGlossaries}, but returns an iterable object. + * + * for-await-of syntax is used with the iterable to recursively get response element on-demand. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the project from which to list all of the glossaries. + * @param {number} [request.pageSize] + * Optional. Requested page size. The server may return fewer glossaries than + * requested. If unspecified, the server picks an appropriate default. + * @param {string} [request.pageToken] + * Optional. A token identifying a page of results the server should return. + * Typically, this is the value of [ListGlossariesResponse.next_page_token] + * returned from the previous call to `ListGlossaries` method. + * The first page is returned if `page_token`is empty or missing. + * @param {string} [request.filter] + * Optional. Filter specifying constraints of a list operation. + * Filtering is not supported yet, and the parameter currently has no effect. + * If missing, no filtering is performed. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that conforms to @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols. + */ + listGlossariesAsync( + request?: protos.google.cloud.translation.v3.IListGlossariesRequest, + options?: gax.CallOptions + ): AsyncIterable { + 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 || '', + }); + options = options || {}; + const callSettings = new gax.CallSettings(options); + this.initialize(); + return this.descriptors.page.listGlossaries.asyncIterate( + this.innerApiCalls['listGlossaries'] as GaxCall, + (request as unknown) as RequestType, + callSettings + ) as AsyncIterable; + } // -------------------- // -- Path templates -- // -------------------- @@ -1296,10 +1431,10 @@ export class TranslationServiceClient { * @returns {string} Resource name string. */ glossaryPath(project: string, location: string, glossary: string) { - return this._pathTemplates.glossaryPathTemplate.render({ - project, - location, - glossary, + return this.pathTemplates.glossaryPathTemplate.render({ + project: project, + location: location, + glossary: glossary, }); } @@ -1311,7 +1446,7 @@ export class TranslationServiceClient { * @returns {string} A string representing the project. */ matchProjectFromGlossaryName(glossaryName: string) { - return this._pathTemplates.glossaryPathTemplate.match(glossaryName).project; + return this.pathTemplates.glossaryPathTemplate.match(glossaryName).project; } /** @@ -1322,8 +1457,7 @@ export class TranslationServiceClient { * @returns {string} A string representing the location. */ matchLocationFromGlossaryName(glossaryName: string) { - return this._pathTemplates.glossaryPathTemplate.match(glossaryName) - .location; + return this.pathTemplates.glossaryPathTemplate.match(glossaryName).location; } /** @@ -1334,8 +1468,7 @@ export class TranslationServiceClient { * @returns {string} A string representing the glossary. */ matchGlossaryFromGlossaryName(glossaryName: string) { - return this._pathTemplates.glossaryPathTemplate.match(glossaryName) - .glossary; + return this.pathTemplates.glossaryPathTemplate.match(glossaryName).glossary; } /** @@ -1346,9 +1479,9 @@ export class TranslationServiceClient { * @returns {string} Resource name string. */ locationPath(project: string, location: string) { - return this._pathTemplates.locationPathTemplate.render({ - project, - location, + return this.pathTemplates.locationPathTemplate.render({ + project: project, + location: location, }); } @@ -1360,7 +1493,7 @@ export class TranslationServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLocationName(locationName: string) { - return this._pathTemplates.locationPathTemplate.match(locationName).project; + return this.pathTemplates.locationPathTemplate.match(locationName).project; } /** @@ -1371,8 +1504,7 @@ export class TranslationServiceClient { * @returns {string} A string representing the location. */ matchLocationFromLocationName(locationName: string) { - return this._pathTemplates.locationPathTemplate.match(locationName) - .location; + return this.pathTemplates.locationPathTemplate.match(locationName).location; } /** diff --git a/src/v3beta1/translation_service_client.ts b/src/v3beta1/translation_service_client.ts index aa932dc0..bb21fdfe 100644 --- a/src/v3beta1/translation_service_client.ts +++ b/src/v3beta1/translation_service_client.ts @@ -18,19 +18,19 @@ import * as gax from 'google-gax'; import { - APICallback, Callback, CallOptions, Descriptors, ClientOptions, LROperation, PaginationCallback, - PaginationResponse, + GaxCall, } from 'google-gax'; import * as path from 'path'; import {Transform} from 'stream'; -import * as protosTypes from '../../protos/protos'; +import {RequestType} from 'google-gax/build/src/apitypes'; +import * as protos from '../../protos/protos'; import * as gapicConfig from './translation_service_client_config.json'; const version = require('../../../package.json').version; @@ -41,14 +41,6 @@ const version = require('../../../package.json').version; * @memberof v3beta1 */ export class TranslationServiceClient { - private _descriptors: Descriptors = { - page: {}, - stream: {}, - longrunning: {}, - batching: {}, - }; - private _innerApiCalls: {[name: string]: Function}; - private _pathTemplates: {[name: string]: gax.PathTemplate}; private _terminated = false; private _opts: ClientOptions; private _gaxModule: typeof gax | typeof gax.fallback; @@ -56,6 +48,14 @@ export class TranslationServiceClient { private _protos: {}; private _defaults: {[method: string]: gax.CallSettings}; auth: gax.GoogleAuth; + descriptors: Descriptors = { + page: {}, + stream: {}, + longrunning: {}, + batching: {}, + }; + innerApiCalls: {[name: string]: Function}; + pathTemplates: {[name: string]: gax.PathTemplate}; operationsClient: gax.OperationsClient; translationServiceStub?: Promise<{[name: string]: Function}>; @@ -148,13 +148,16 @@ export class TranslationServiceClient { 'protos.json' ); this._protos = this._gaxGrpc.loadProto( - opts.fallback ? require('../../protos/protos.json') : nodejsProtoPath + opts.fallback + ? // eslint-disable-next-line @typescript-eslint/no-var-requires + require('../../protos/protos.json') + : nodejsProtoPath ); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. - this._pathTemplates = { + this.pathTemplates = { glossaryPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/locations/{location}/glossaries/{glossary}' ), @@ -166,7 +169,7 @@ export class TranslationServiceClient { // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. - this._descriptors.page = { + this.descriptors.page = { listGlossaries: new this._gaxModule.PageDescriptor( 'pageToken', 'nextPageToken', @@ -179,6 +182,7 @@ export class TranslationServiceClient { // rather than holding a request open. const protoFilesRoot = opts.fallback ? this._gaxModule.protobuf.Root.fromJSON( + // eslint-disable-next-line @typescript-eslint/no-var-requires require('../../protos/protos.json') ) : this._gaxModule.protobuf.loadSync(nodejsProtoPath); @@ -208,7 +212,7 @@ export class TranslationServiceClient { '.google.cloud.translation.v3beta1.DeleteGlossaryMetadata' ) as gax.protobuf.Type; - this._descriptors.longrunning = { + this.descriptors.longrunning = { batchTranslateText: new this._gaxModule.LongrunningDescriptor( this.operationsClient, batchTranslateTextResponse.decode.bind(batchTranslateTextResponse), @@ -237,7 +241,7 @@ export class TranslationServiceClient { // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code // merely providing the destination and request information. - this._innerApiCalls = {}; + this.innerApiCalls = {}; } /** @@ -264,7 +268,7 @@ export class TranslationServiceClient { ? (this._protos as protobuf.Root).lookupService( 'google.cloud.translation.v3beta1.TranslationService' ) - : // tslint:disable-next-line no-any + : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.translation.v3beta1 .TranslationService, this._opts @@ -282,9 +286,8 @@ export class TranslationServiceClient { 'getGlossary', 'deleteGlossary', ]; - for (const methodName of translationServiceStubMethods) { - const innerCallPromise = this.translationServiceStub.then( + const callPromise = this.translationServiceStub.then( stub => (...args: Array<{}>) => { if (this._terminated) { return Promise.reject('The client has already been closed.'); @@ -298,20 +301,14 @@ export class TranslationServiceClient { ); const apiCall = this._gaxModule.createApiCall( - innerCallPromise, + callPromise, this._defaults[methodName], - this._descriptors.page[methodName] || - this._descriptors.stream[methodName] || - this._descriptors.longrunning[methodName] + this.descriptors.page[methodName] || + this.descriptors.stream[methodName] || + this.descriptors.longrunning[methodName] ); - this._innerApiCalls[methodName] = ( - argument: {}, - callOptions?: CallOptions, - callback?: APICallback - ) => { - return apiCall(argument, callOptions, callback); - }; + this.innerApiCalls[methodName] = apiCall; } return this.translationServiceStub; @@ -371,26 +368,34 @@ export class TranslationServiceClient { // -- Service calls -- // ------------------- translateText( - request: protosTypes.google.cloud.translation.v3beta1.ITranslateTextRequest, + request: protos.google.cloud.translation.v3beta1.ITranslateTextRequest, options?: gax.CallOptions ): Promise< [ - protosTypes.google.cloud.translation.v3beta1.ITranslateTextResponse, - ( - | protosTypes.google.cloud.translation.v3beta1.ITranslateTextRequest - | undefined - ), + protos.google.cloud.translation.v3beta1.ITranslateTextResponse, + protos.google.cloud.translation.v3beta1.ITranslateTextRequest | undefined, {} | undefined ] >; translateText( - request: protosTypes.google.cloud.translation.v3beta1.ITranslateTextRequest, + request: protos.google.cloud.translation.v3beta1.ITranslateTextRequest, options: gax.CallOptions, callback: Callback< - protosTypes.google.cloud.translation.v3beta1.ITranslateTextResponse, - | protosTypes.google.cloud.translation.v3beta1.ITranslateTextRequest + protos.google.cloud.translation.v3beta1.ITranslateTextResponse, + | protos.google.cloud.translation.v3beta1.ITranslateTextRequest + | null | undefined, - {} | undefined + {} | null | undefined + > + ): void; + translateText( + request: protos.google.cloud.translation.v3beta1.ITranslateTextRequest, + callback: Callback< + protos.google.cloud.translation.v3beta1.ITranslateTextResponse, + | protos.google.cloud.translation.v3beta1.ITranslateTextRequest + | null + | undefined, + {} | null | undefined > ): void; /** @@ -467,28 +472,27 @@ export class TranslationServiceClient { * The promise has a method named "cancel" which cancels the ongoing API call. */ translateText( - request: protosTypes.google.cloud.translation.v3beta1.ITranslateTextRequest, + request: protos.google.cloud.translation.v3beta1.ITranslateTextRequest, optionsOrCallback?: | gax.CallOptions | Callback< - protosTypes.google.cloud.translation.v3beta1.ITranslateTextResponse, - | protosTypes.google.cloud.translation.v3beta1.ITranslateTextRequest + protos.google.cloud.translation.v3beta1.ITranslateTextResponse, + | protos.google.cloud.translation.v3beta1.ITranslateTextRequest + | null | undefined, - {} | undefined + {} | null | undefined >, callback?: Callback< - protosTypes.google.cloud.translation.v3beta1.ITranslateTextResponse, - | protosTypes.google.cloud.translation.v3beta1.ITranslateTextRequest + protos.google.cloud.translation.v3beta1.ITranslateTextResponse, + | protos.google.cloud.translation.v3beta1.ITranslateTextRequest + | null | undefined, - {} | undefined + {} | null | undefined > ): Promise< [ - protosTypes.google.cloud.translation.v3beta1.ITranslateTextResponse, - ( - | protosTypes.google.cloud.translation.v3beta1.ITranslateTextRequest - | undefined - ), + protos.google.cloud.translation.v3beta1.ITranslateTextResponse, + protos.google.cloud.translation.v3beta1.ITranslateTextRequest | undefined, {} | undefined ] > | void { @@ -509,29 +513,40 @@ export class TranslationServiceClient { parent: request.parent || '', }); this.initialize(); - return this._innerApiCalls.translateText(request, options, callback); + return this.innerApiCalls.translateText(request, options, callback); } detectLanguage( - request: protosTypes.google.cloud.translation.v3beta1.IDetectLanguageRequest, + request: protos.google.cloud.translation.v3beta1.IDetectLanguageRequest, options?: gax.CallOptions ): Promise< [ - protosTypes.google.cloud.translation.v3beta1.IDetectLanguageResponse, + protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, ( - | protosTypes.google.cloud.translation.v3beta1.IDetectLanguageRequest + | protos.google.cloud.translation.v3beta1.IDetectLanguageRequest | undefined ), {} | undefined ] >; detectLanguage( - request: protosTypes.google.cloud.translation.v3beta1.IDetectLanguageRequest, + request: protos.google.cloud.translation.v3beta1.IDetectLanguageRequest, options: gax.CallOptions, callback: Callback< - protosTypes.google.cloud.translation.v3beta1.IDetectLanguageResponse, - | protosTypes.google.cloud.translation.v3beta1.IDetectLanguageRequest + protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, + | protos.google.cloud.translation.v3beta1.IDetectLanguageRequest + | null | undefined, - {} | undefined + {} | null | undefined + > + ): void; + detectLanguage( + request: protos.google.cloud.translation.v3beta1.IDetectLanguageRequest, + callback: Callback< + protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, + | protos.google.cloud.translation.v3beta1.IDetectLanguageRequest + | null + | undefined, + {} | null | undefined > ): void; /** @@ -582,26 +597,28 @@ export class TranslationServiceClient { * The promise has a method named "cancel" which cancels the ongoing API call. */ detectLanguage( - request: protosTypes.google.cloud.translation.v3beta1.IDetectLanguageRequest, + request: protos.google.cloud.translation.v3beta1.IDetectLanguageRequest, optionsOrCallback?: | gax.CallOptions | Callback< - protosTypes.google.cloud.translation.v3beta1.IDetectLanguageResponse, - | protosTypes.google.cloud.translation.v3beta1.IDetectLanguageRequest + protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, + | protos.google.cloud.translation.v3beta1.IDetectLanguageRequest + | null | undefined, - {} | undefined + {} | null | undefined >, callback?: Callback< - protosTypes.google.cloud.translation.v3beta1.IDetectLanguageResponse, - | protosTypes.google.cloud.translation.v3beta1.IDetectLanguageRequest + protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, + | protos.google.cloud.translation.v3beta1.IDetectLanguageRequest + | null | undefined, - {} | undefined + {} | null | undefined > ): Promise< [ - protosTypes.google.cloud.translation.v3beta1.IDetectLanguageResponse, + protos.google.cloud.translation.v3beta1.IDetectLanguageResponse, ( - | protosTypes.google.cloud.translation.v3beta1.IDetectLanguageRequest + | protos.google.cloud.translation.v3beta1.IDetectLanguageRequest | undefined ), {} | undefined @@ -624,29 +641,40 @@ export class TranslationServiceClient { parent: request.parent || '', }); this.initialize(); - return this._innerApiCalls.detectLanguage(request, options, callback); + return this.innerApiCalls.detectLanguage(request, options, callback); } getSupportedLanguages( - request: protosTypes.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest, + request: protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest, options?: gax.CallOptions ): Promise< [ - protosTypes.google.cloud.translation.v3beta1.ISupportedLanguages, + protos.google.cloud.translation.v3beta1.ISupportedLanguages, ( - | protosTypes.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + | protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest | undefined ), {} | undefined ] >; getSupportedLanguages( - request: protosTypes.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest, + request: protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest, options: gax.CallOptions, callback: Callback< - protosTypes.google.cloud.translation.v3beta1.ISupportedLanguages, - | protosTypes.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + protos.google.cloud.translation.v3beta1.ISupportedLanguages, + | protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + | null | undefined, - {} | undefined + {} | null | undefined + > + ): void; + getSupportedLanguages( + request: protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest, + callback: Callback< + protos.google.cloud.translation.v3beta1.ISupportedLanguages, + | protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + | null + | undefined, + {} | null | undefined > ): void; /** @@ -694,26 +722,28 @@ export class TranslationServiceClient { * The promise has a method named "cancel" which cancels the ongoing API call. */ getSupportedLanguages( - request: protosTypes.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest, + request: protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest, optionsOrCallback?: | gax.CallOptions | Callback< - protosTypes.google.cloud.translation.v3beta1.ISupportedLanguages, - | protosTypes.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + protos.google.cloud.translation.v3beta1.ISupportedLanguages, + | protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + | null | undefined, - {} | undefined + {} | null | undefined >, callback?: Callback< - protosTypes.google.cloud.translation.v3beta1.ISupportedLanguages, - | protosTypes.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + protos.google.cloud.translation.v3beta1.ISupportedLanguages, + | protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + | null | undefined, - {} | undefined + {} | null | undefined > ): Promise< [ - protosTypes.google.cloud.translation.v3beta1.ISupportedLanguages, + protos.google.cloud.translation.v3beta1.ISupportedLanguages, ( - | protosTypes.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest + | protos.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest | undefined ), {} | undefined @@ -736,33 +766,37 @@ export class TranslationServiceClient { parent: request.parent || '', }); this.initialize(); - return this._innerApiCalls.getSupportedLanguages( - request, - options, - callback - ); + return this.innerApiCalls.getSupportedLanguages(request, options, callback); } getGlossary( - request: protosTypes.google.cloud.translation.v3beta1.IGetGlossaryRequest, + request: protos.google.cloud.translation.v3beta1.IGetGlossaryRequest, options?: gax.CallOptions ): Promise< [ - protosTypes.google.cloud.translation.v3beta1.IGlossary, - ( - | protosTypes.google.cloud.translation.v3beta1.IGetGlossaryRequest - | undefined - ), + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.IGetGlossaryRequest | undefined, {} | undefined ] >; getGlossary( - request: protosTypes.google.cloud.translation.v3beta1.IGetGlossaryRequest, + request: protos.google.cloud.translation.v3beta1.IGetGlossaryRequest, options: gax.CallOptions, callback: Callback< - protosTypes.google.cloud.translation.v3beta1.IGlossary, - | protosTypes.google.cloud.translation.v3beta1.IGetGlossaryRequest + protos.google.cloud.translation.v3beta1.IGlossary, + | protos.google.cloud.translation.v3beta1.IGetGlossaryRequest + | null | undefined, - {} | undefined + {} | null | undefined + > + ): void; + getGlossary( + request: protos.google.cloud.translation.v3beta1.IGetGlossaryRequest, + callback: Callback< + protos.google.cloud.translation.v3beta1.IGlossary, + | protos.google.cloud.translation.v3beta1.IGetGlossaryRequest + | null + | undefined, + {} | null | undefined > ): void; /** @@ -780,28 +814,27 @@ export class TranslationServiceClient { * The promise has a method named "cancel" which cancels the ongoing API call. */ getGlossary( - request: protosTypes.google.cloud.translation.v3beta1.IGetGlossaryRequest, + request: protos.google.cloud.translation.v3beta1.IGetGlossaryRequest, optionsOrCallback?: | gax.CallOptions | Callback< - protosTypes.google.cloud.translation.v3beta1.IGlossary, - | protosTypes.google.cloud.translation.v3beta1.IGetGlossaryRequest + protos.google.cloud.translation.v3beta1.IGlossary, + | protos.google.cloud.translation.v3beta1.IGetGlossaryRequest + | null | undefined, - {} | undefined + {} | null | undefined >, callback?: Callback< - protosTypes.google.cloud.translation.v3beta1.IGlossary, - | protosTypes.google.cloud.translation.v3beta1.IGetGlossaryRequest + protos.google.cloud.translation.v3beta1.IGlossary, + | protos.google.cloud.translation.v3beta1.IGetGlossaryRequest + | null | undefined, - {} | undefined + {} | null | undefined > ): Promise< [ - protosTypes.google.cloud.translation.v3beta1.IGlossary, - ( - | protosTypes.google.cloud.translation.v3beta1.IGetGlossaryRequest - | undefined - ), + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.IGetGlossaryRequest | undefined, {} | undefined ] > | void { @@ -822,32 +855,43 @@ export class TranslationServiceClient { name: request.name || '', }); this.initialize(); - return this._innerApiCalls.getGlossary(request, options, callback); + return this.innerApiCalls.getGlossary(request, options, callback); } batchTranslateText( - request: protosTypes.google.cloud.translation.v3beta1.IBatchTranslateTextRequest, + request: protos.google.cloud.translation.v3beta1.IBatchTranslateTextRequest, options?: gax.CallOptions ): Promise< [ LROperation< - protosTypes.google.cloud.translation.v3beta1.IBatchTranslateResponse, - protosTypes.google.cloud.translation.v3beta1.IBatchTranslateMetadata + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata >, - protosTypes.google.longrunning.IOperation | undefined, + protos.google.longrunning.IOperation | undefined, {} | undefined ] >; batchTranslateText( - request: protosTypes.google.cloud.translation.v3beta1.IBatchTranslateTextRequest, + request: protos.google.cloud.translation.v3beta1.IBatchTranslateTextRequest, options: gax.CallOptions, callback: Callback< LROperation< - protosTypes.google.cloud.translation.v3beta1.IBatchTranslateResponse, - protosTypes.google.cloud.translation.v3beta1.IBatchTranslateMetadata + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + batchTranslateText( + request: protos.google.cloud.translation.v3beta1.IBatchTranslateTextRequest, + callback: Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined > ): void; /** @@ -920,32 +964,32 @@ export class TranslationServiceClient { * The promise has a method named "cancel" which cancels the ongoing API call. */ batchTranslateText( - request: protosTypes.google.cloud.translation.v3beta1.IBatchTranslateTextRequest, + request: protos.google.cloud.translation.v3beta1.IBatchTranslateTextRequest, optionsOrCallback?: | gax.CallOptions | Callback< LROperation< - protosTypes.google.cloud.translation.v3beta1.IBatchTranslateResponse, - protosTypes.google.cloud.translation.v3beta1.IBatchTranslateMetadata + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined >, callback?: Callback< LROperation< - protosTypes.google.cloud.translation.v3beta1.IBatchTranslateResponse, - protosTypes.google.cloud.translation.v3beta1.IBatchTranslateMetadata + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined > ): Promise< [ LROperation< - protosTypes.google.cloud.translation.v3beta1.IBatchTranslateResponse, - protosTypes.google.cloud.translation.v3beta1.IBatchTranslateMetadata + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata >, - protosTypes.google.longrunning.IOperation | undefined, + protos.google.longrunning.IOperation | undefined, {} | undefined ] > | void { @@ -966,31 +1010,42 @@ export class TranslationServiceClient { parent: request.parent || '', }); this.initialize(); - return this._innerApiCalls.batchTranslateText(request, options, callback); + return this.innerApiCalls.batchTranslateText(request, options, callback); } createGlossary( - request: protosTypes.google.cloud.translation.v3beta1.ICreateGlossaryRequest, + request: protos.google.cloud.translation.v3beta1.ICreateGlossaryRequest, options?: gax.CallOptions ): Promise< [ LROperation< - protosTypes.google.cloud.translation.v3beta1.IGlossary, - protosTypes.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata >, - protosTypes.google.longrunning.IOperation | undefined, + protos.google.longrunning.IOperation | undefined, {} | undefined ] >; createGlossary( - request: protosTypes.google.cloud.translation.v3beta1.ICreateGlossaryRequest, + request: protos.google.cloud.translation.v3beta1.ICreateGlossaryRequest, options: gax.CallOptions, callback: Callback< LROperation< - protosTypes.google.cloud.translation.v3beta1.IGlossary, - protosTypes.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + createGlossary( + request: protos.google.cloud.translation.v3beta1.ICreateGlossaryRequest, + callback: Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined > ): void; /** @@ -1010,32 +1065,32 @@ export class TranslationServiceClient { * The promise has a method named "cancel" which cancels the ongoing API call. */ createGlossary( - request: protosTypes.google.cloud.translation.v3beta1.ICreateGlossaryRequest, + request: protos.google.cloud.translation.v3beta1.ICreateGlossaryRequest, optionsOrCallback?: | gax.CallOptions | Callback< LROperation< - protosTypes.google.cloud.translation.v3beta1.IGlossary, - protosTypes.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined >, callback?: Callback< LROperation< - protosTypes.google.cloud.translation.v3beta1.IGlossary, - protosTypes.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined > ): Promise< [ LROperation< - protosTypes.google.cloud.translation.v3beta1.IGlossary, - protosTypes.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata >, - protosTypes.google.longrunning.IOperation | undefined, + protos.google.longrunning.IOperation | undefined, {} | undefined ] > | void { @@ -1056,31 +1111,42 @@ export class TranslationServiceClient { parent: request.parent || '', }); this.initialize(); - return this._innerApiCalls.createGlossary(request, options, callback); + return this.innerApiCalls.createGlossary(request, options, callback); } deleteGlossary( - request: protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryRequest, + request: protos.google.cloud.translation.v3beta1.IDeleteGlossaryRequest, options?: gax.CallOptions ): Promise< [ LROperation< - protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, - protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata >, - protosTypes.google.longrunning.IOperation | undefined, + protos.google.longrunning.IOperation | undefined, {} | undefined ] >; deleteGlossary( - request: protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryRequest, + request: protos.google.cloud.translation.v3beta1.IDeleteGlossaryRequest, options: gax.CallOptions, callback: Callback< LROperation< - protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, - protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined + > + ): void; + deleteGlossary( + request: protos.google.cloud.translation.v3beta1.IDeleteGlossaryRequest, + callback: Callback< + LROperation< + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + >, + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined > ): void; /** @@ -1099,32 +1165,32 @@ export class TranslationServiceClient { * The promise has a method named "cancel" which cancels the ongoing API call. */ deleteGlossary( - request: protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryRequest, + request: protos.google.cloud.translation.v3beta1.IDeleteGlossaryRequest, optionsOrCallback?: | gax.CallOptions | Callback< LROperation< - protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, - protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined >, callback?: Callback< LROperation< - protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, - protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined + protos.google.longrunning.IOperation | null | undefined, + {} | null | undefined > ): Promise< [ LROperation< - protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, - protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata >, - protosTypes.google.longrunning.IOperation | undefined, + protos.google.longrunning.IOperation | undefined, {} | undefined ] > | void { @@ -1145,25 +1211,37 @@ export class TranslationServiceClient { name: request.name || '', }); this.initialize(); - return this._innerApiCalls.deleteGlossary(request, options, callback); + return this.innerApiCalls.deleteGlossary(request, options, callback); } listGlossaries( - request: protosTypes.google.cloud.translation.v3beta1.IListGlossariesRequest, + request: protos.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 + protos.google.cloud.translation.v3beta1.IGlossary[], + protos.google.cloud.translation.v3beta1.IListGlossariesRequest | null, + protos.google.cloud.translation.v3beta1.IListGlossariesResponse ] >; listGlossaries( - request: protosTypes.google.cloud.translation.v3beta1.IListGlossariesRequest, + request: protos.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 + callback: PaginationCallback< + protos.google.cloud.translation.v3beta1.IListGlossariesRequest, + | protos.google.cloud.translation.v3beta1.IListGlossariesResponse + | null + | undefined, + protos.google.cloud.translation.v3beta1.IGlossary + > + ): void; + listGlossaries( + request: protos.google.cloud.translation.v3beta1.IListGlossariesRequest, + callback: PaginationCallback< + protos.google.cloud.translation.v3beta1.IListGlossariesRequest, + | protos.google.cloud.translation.v3beta1.IListGlossariesResponse + | null + | undefined, + protos.google.cloud.translation.v3beta1.IGlossary > ): void; /** @@ -1205,24 +1283,28 @@ export class TranslationServiceClient { * The promise has a method named "cancel" which cancels the ongoing API call. */ listGlossaries( - request: protosTypes.google.cloud.translation.v3beta1.IListGlossariesRequest, + request: protos.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 + | PaginationCallback< + protos.google.cloud.translation.v3beta1.IListGlossariesRequest, + | protos.google.cloud.translation.v3beta1.IListGlossariesResponse + | null + | undefined, + protos.google.cloud.translation.v3beta1.IGlossary >, - callback?: Callback< - protosTypes.google.cloud.translation.v3beta1.IGlossary[], - protosTypes.google.cloud.translation.v3beta1.IListGlossariesRequest | null, - protosTypes.google.cloud.translation.v3beta1.IListGlossariesResponse + callback?: PaginationCallback< + protos.google.cloud.translation.v3beta1.IListGlossariesRequest, + | protos.google.cloud.translation.v3beta1.IListGlossariesResponse + | null + | undefined, + protos.google.cloud.translation.v3beta1.IGlossary > ): Promise< [ - protosTypes.google.cloud.translation.v3beta1.IGlossary[], - protosTypes.google.cloud.translation.v3beta1.IListGlossariesRequest | null, - protosTypes.google.cloud.translation.v3beta1.IListGlossariesResponse + protos.google.cloud.translation.v3beta1.IGlossary[], + protos.google.cloud.translation.v3beta1.IListGlossariesRequest | null, + protos.google.cloud.translation.v3beta1.IListGlossariesResponse ] > | void { request = request || {}; @@ -1242,7 +1324,7 @@ export class TranslationServiceClient { parent: request.parent || '', }); this.initialize(); - return this._innerApiCalls.listGlossaries(request, options, callback); + return this.innerApiCalls.listGlossaries(request, options, callback); } /** @@ -1280,7 +1362,7 @@ export class TranslationServiceClient { * An object stream which emits an object representing [Glossary]{@link google.cloud.translation.v3beta1.Glossary} on 'data' event. */ listGlossariesStream( - request?: protosTypes.google.cloud.translation.v3beta1.IListGlossariesRequest, + request?: protos.google.cloud.translation.v3beta1.IListGlossariesRequest, options?: gax.CallOptions ): Transform { request = request || {}; @@ -1294,12 +1376,61 @@ export class TranslationServiceClient { }); const callSettings = new gax.CallSettings(options); this.initialize(); - return this._descriptors.page.listGlossaries.createStream( - this._innerApiCalls.listGlossaries as gax.GaxCall, + return this.descriptors.page.listGlossaries.createStream( + this.innerApiCalls.listGlossaries as gax.GaxCall, request, callSettings ); } + + /** + * Equivalent to {@link listGlossaries}, but returns an iterable object. + * + * for-await-of syntax is used with the iterable to recursively get response element on-demand. + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.parent + * Required. The name of the project from which to list all of the glossaries. + * @param {number} [request.pageSize] + * Optional. Requested page size. The server may return fewer glossaries than + * requested. If unspecified, the server picks an appropriate default. + * @param {string} [request.pageToken] + * Optional. A token identifying a page of results the server should return. + * Typically, this is the value of [ListGlossariesResponse.next_page_token] + * returned from the previous call to `ListGlossaries` method. + * The first page is returned if `page_token`is empty or missing. + * @param {string} [request.filter] + * Optional. Filter specifying constraints of a list operation. + * Filtering is not supported yet, and the parameter currently has no effect. + * If missing, no filtering is performed. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Object} + * An iterable Object that conforms to @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols. + */ + listGlossariesAsync( + request?: protos.google.cloud.translation.v3beta1.IListGlossariesRequest, + options?: gax.CallOptions + ): AsyncIterable { + 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 || '', + }); + options = options || {}; + const callSettings = new gax.CallSettings(options); + this.initialize(); + return this.descriptors.page.listGlossaries.asyncIterate( + this.innerApiCalls['listGlossaries'] as GaxCall, + (request as unknown) as RequestType, + callSettings + ) as AsyncIterable; + } // -------------------- // -- Path templates -- // -------------------- @@ -1313,10 +1444,10 @@ export class TranslationServiceClient { * @returns {string} Resource name string. */ glossaryPath(project: string, location: string, glossary: string) { - return this._pathTemplates.glossaryPathTemplate.render({ - project, - location, - glossary, + return this.pathTemplates.glossaryPathTemplate.render({ + project: project, + location: location, + glossary: glossary, }); } @@ -1328,7 +1459,7 @@ export class TranslationServiceClient { * @returns {string} A string representing the project. */ matchProjectFromGlossaryName(glossaryName: string) { - return this._pathTemplates.glossaryPathTemplate.match(glossaryName).project; + return this.pathTemplates.glossaryPathTemplate.match(glossaryName).project; } /** @@ -1339,8 +1470,7 @@ export class TranslationServiceClient { * @returns {string} A string representing the location. */ matchLocationFromGlossaryName(glossaryName: string) { - return this._pathTemplates.glossaryPathTemplate.match(glossaryName) - .location; + return this.pathTemplates.glossaryPathTemplate.match(glossaryName).location; } /** @@ -1351,8 +1481,7 @@ export class TranslationServiceClient { * @returns {string} A string representing the glossary. */ matchGlossaryFromGlossaryName(glossaryName: string) { - return this._pathTemplates.glossaryPathTemplate.match(glossaryName) - .glossary; + return this.pathTemplates.glossaryPathTemplate.match(glossaryName).glossary; } /** @@ -1363,9 +1492,9 @@ export class TranslationServiceClient { * @returns {string} Resource name string. */ locationPath(project: string, location: string) { - return this._pathTemplates.locationPathTemplate.render({ - project, - location, + return this.pathTemplates.locationPathTemplate.render({ + project: project, + location: location, }); } @@ -1377,7 +1506,7 @@ export class TranslationServiceClient { * @returns {string} A string representing the project. */ matchProjectFromLocationName(locationName: string) { - return this._pathTemplates.locationPathTemplate.match(locationName).project; + return this.pathTemplates.locationPathTemplate.match(locationName).project; } /** @@ -1388,8 +1517,7 @@ export class TranslationServiceClient { * @returns {string} A string representing the location. */ matchLocationFromLocationName(locationName: string) { - return this._pathTemplates.locationPathTemplate.match(locationName) - .location; + return this.pathTemplates.locationPathTemplate.match(locationName).location; } /** diff --git a/synth.metadata b/synth.metadata index d52836d4..52170167 100644 --- a/synth.metadata +++ b/synth.metadata @@ -1,23 +1,5 @@ { - "updateTime": "2020-03-22T11:53:00.105404Z", - "sources": [ - { - "git": { - "name": "googleapis", - "remote": "https://github.com/googleapis/googleapis.git", - "sha": "0be7105dc52590fa9a24e784052298ae37ce53aa", - "internalRef": "302154871", - "log": "0be7105dc52590fa9a24e784052298ae37ce53aa\nAdd BUILD.bazel file to asset/v1p1beta1\n\nPiperOrigin-RevId: 302154871\n\n6c248fd13e8543f8d22cbf118d978301a9fbe2a8\nAdd missing resource annotations and additional_bindings to dialogflow v2 API.\n\nPiperOrigin-RevId: 302063117\n\n9a3a7f33be9eeacf7b3e98435816b7022d206bd7\nChange the service name from \"chromeos-moblab.googleapis.com\" to \"chromeosmoblab.googleapis.com\"\n\nPiperOrigin-RevId: 302060989\n\n98a339237577e3de26cb4921f75fb5c57cc7a19f\nfeat: devtools/build/v1 publish client library config annotations\n\n* add details field to some of the BuildEvents\n* add final_invocation_id and build_tool_exit_code fields to BuildStatus\n\nPiperOrigin-RevId: 302044087\n\ncfabc98c6bbbb22d1aeaf7612179c0be193b3a13\nfeat: home/graph/v1 publish client library config annotations & comment updates\n\nThis change includes adding the client library configuration annotations, updated proto comments, and some client library configuration files.\n\nPiperOrigin-RevId: 302042647\n\nc8c8c0bd15d082db9546253dbaad1087c7a9782c\nchore: use latest gapic-generator in bazel WORKSPACE.\nincluding the following commits from gapic-generator:\n- feat: take source protos in all sub-packages (#3144)\n\nPiperOrigin-RevId: 301843591\n\ne4daf5202ea31cb2cb6916fdbfa9d6bd771aeb4c\nAdd bazel file for v1 client lib generation\n\nPiperOrigin-RevId: 301802926\n\n275fbcce2c900278d487c33293a3c7e1fbcd3a34\nfeat: pubsub/v1 add an experimental filter field to Subscription\n\nPiperOrigin-RevId: 301661567\n\nf2b18cec51d27c999ad30011dba17f3965677e9c\nFix: UpdateBackupRequest.backup is a resource, not a resource reference - remove annotation.\n\nPiperOrigin-RevId: 301636171\n\n800384063ac93a0cac3a510d41726fa4b2cd4a83\nCloud Billing Budget API v1beta1\nModified api documentation to include warnings about the new filter field.\n\nPiperOrigin-RevId: 301634389\n\n0cc6c146b660db21f04056c3d58a4b752ee445e3\nCloud Billing Budget API v1alpha1\nModified api documentation to include warnings about the new filter field.\n\nPiperOrigin-RevId: 301630018\n\nff2ea00f69065585c3ac0993c8b582af3b6fc215\nFix: Add resource definition for a parent of InspectTemplate which was otherwise missing.\n\nPiperOrigin-RevId: 301623052\n\n55fa441c9daf03173910760191646399338f2b7c\nAdd proto definition for AccessLevel, AccessPolicy, and ServicePerimeter.\n\nPiperOrigin-RevId: 301620844\n\ne7b10591c5408a67cf14ffafa267556f3290e262\nCloud Bigtable Managed Backup service and message proto files.\n\nPiperOrigin-RevId: 301585144\n\nd8e226f702f8ddf92915128c9f4693b63fb8685d\nfeat: Add time-to-live in a queue for builds\n\nPiperOrigin-RevId: 301579876\n\n430375af011f8c7a5174884f0d0e539c6ffa7675\ndocs: add missing closing backtick\n\nPiperOrigin-RevId: 301538851\n\n0e9f1f60ded9ad1c2e725e37719112f5b487ab65\nbazel: Use latest release of gax_java\n\nPiperOrigin-RevId: 301480457\n\n5058c1c96d0ece7f5301a154cf5a07b2ad03a571\nUpdate GAPIC v2 with batching parameters for Logging API\n\nPiperOrigin-RevId: 301443847\n\n64ab9744073de81fec1b3a6a931befc8a90edf90\nFix: Introduce location-based organization/folder/billing-account resources\nChore: Update copyright years\n\nPiperOrigin-RevId: 301373760\n\n23d5f09e670ebb0c1b36214acf78704e2ecfc2ac\nUpdate field_behavior annotations in V1 and V2.\n\nPiperOrigin-RevId: 301337970\n\nb2cf37e7fd62383a811aa4d54d013ecae638851d\nData Catalog V1 API\n\nPiperOrigin-RevId: 301282503\n\n1976b9981e2900c8172b7d34b4220bdb18c5db42\nCloud DLP api update. Adds missing fields to Finding and adds support for hybrid jobs.\n\nPiperOrigin-RevId: 301205325\n\nae78682c05e864d71223ce22532219813b0245ac\nfix: several sample code blocks in comments are now properly indented for markdown\n\nPiperOrigin-RevId: 301185150\n\ndcd171d04bda5b67db13049320f97eca3ace3731\nPublish Media Translation API V1Beta1\n\nPiperOrigin-RevId: 301180096\n\nff1713453b0fbc5a7544a1ef6828c26ad21a370e\nAdd protos and BUILD rules for v1 API.\n\nPiperOrigin-RevId: 301179394\n\n8386761d09819b665b6a6e1e6d6ff884bc8ff781\nfeat: chromeos/modlab publish protos and config for Chrome OS Moblab API.\n\nPiperOrigin-RevId: 300843960\n\nb2e2bc62fab90e6829e62d3d189906d9b79899e4\nUpdates to GCS gRPC API spec:\n\n1. Changed GetIamPolicy and TestBucketIamPermissions to use wrapper messages around google.iam.v1 IAM requests messages, and added CommonRequestParams. This lets us support RequesterPays buckets.\n2. Added a metadata field to GetObjectMediaResponse, to support resuming an object media read safely (by extracting the generation of the object being read, and using it in the resumed read request).\n\nPiperOrigin-RevId: 300817706\n\n7fd916ce12335cc9e784bb9452a8602d00b2516c\nAdd deprecated_collections field for backward-compatiblity in PHP and monolith-generated Python and Ruby clients.\n\nGenerate TopicName class in Java which covers the functionality of both ProjectTopicName and DeletedTopicName. Introduce breaking changes to be fixed by synth.py.\n\nDelete default retry parameters.\n\nRetry codes defs can be deleted once # https://github.com/googleapis/gapic-generator/issues/3137 is fixed.\n\nPiperOrigin-RevId: 300813135\n\n047d3a8ac7f75383855df0166144f891d7af08d9\nfix!: google/rpc refactor ErrorInfo.type to ErrorInfo.reason and comment updates.\n\nPiperOrigin-RevId: 300773211\n\nfae4bb6d5aac52aabe5f0bb4396466c2304ea6f6\nAdding RetryPolicy to pubsub.proto\n\nPiperOrigin-RevId: 300769420\n\n7d569be2928dbd72b4e261bf9e468f23afd2b950\nAdding additional protocol buffer annotations to v3.\n\nPiperOrigin-RevId: 300718800\n\n13942d1a85a337515040a03c5108993087dc0e4f\nAdd logging protos for Recommender v1.\n\nPiperOrigin-RevId: 300689896\n\na1a573c3eecfe2c404892bfa61a32dd0c9fb22b6\nfix: change go package to use cloud.google.com/go/maps\n\nPiperOrigin-RevId: 300661825\n\nc6fbac11afa0c7ab2972d9df181493875c566f77\nfeat: publish documentai/v1beta2 protos\n\nPiperOrigin-RevId: 300656808\n\n5202a9e0d9903f49e900f20fe5c7f4e42dd6588f\nProtos for v1beta1 release of Cloud Security Center Settings API\n\nPiperOrigin-RevId: 300580858\n\n83518e18655d9d4ac044acbda063cc6ecdb63ef8\nAdds gapic.yaml file and BUILD.bazel file.\n\nPiperOrigin-RevId: 300554200\n\n836c196dc8ef8354bbfb5f30696bd3477e8db5e2\nRegenerate recommender v1beta1 gRPC ServiceConfig file for Insights methods.\n\nPiperOrigin-RevId: 300549302\n\n34a5450c591b6be3d6566f25ac31caa5211b2f3f\nIncreases the default timeout from 20s to 30s for MetricService\n\nPiperOrigin-RevId: 300474272\n\n5d8bffe87cd01ba390c32f1714230e5a95d5991d\nfeat: use the latest gapic-generator in WORKSPACE for bazel build.\n\nPiperOrigin-RevId: 300461878\n\nd631c651e3bcfac5d371e8560c27648f7b3e2364\nUpdated the GAPIC configs to include parameters for Backups APIs.\n\nPiperOrigin-RevId: 300443402\n\n678afc7055c1adea9b7b54519f3bdb228013f918\nAdding Game Servers v1beta API.\n\nPiperOrigin-RevId: 300433218\n\n80d2bd2c652a5e213302041b0620aff423132589\nEnable proto annotation and gapic v2 for talent API.\n\nPiperOrigin-RevId: 300393997\n\n85e454be7a353f7fe1bf2b0affb753305785b872\ndocs(google/maps/roads): remove mention of nonexported api\n\nPiperOrigin-RevId: 300367734\n\nbf839ae632e0f263a729569e44be4b38b1c85f9c\nAdding protocol buffer annotations and updated config info for v1 and v2.\n\nPiperOrigin-RevId: 300276913\n\n309b899ca18a4c604bce63882a161d44854da549\nPublish `Backup` APIs and protos.\n\nPiperOrigin-RevId: 300246038\n\neced64c3f122421350b4aca68a28e89121d20db8\nadd PHP client libraries\n\nPiperOrigin-RevId: 300193634\n\n7727af0e39df1ae9ad715895c8576d7b65cf6c6d\nfeat: use the latest gapic-generator and protoc-java-resource-name-plugin in googleapis/WORKSPACE.\n\nPiperOrigin-RevId: 300188410\n\n2a25aa351dd5b5fe14895266aff5824d90ce757b\nBreaking change: remove the ProjectOrTenant resource and its references.\n\nPiperOrigin-RevId: 300182152\n\na499dbb28546379415f51803505cfb6123477e71\nUpdate web risk v1 gapic config and BUILD file.\n\nPiperOrigin-RevId: 300152177\n\n52701da10fec2a5f9796e8d12518c0fe574488fe\nFix: apply appropriate namespace/package options for C#, PHP and Ruby.\n\nPiperOrigin-RevId: 300123508\n\n365c029b8cdb63f7751b92ab490f1976e616105c\nAdd CC targets to the kms protos.\n\nThese are needed by go/tink.\n\nPiperOrigin-RevId: 300038469\n\n4ba9aa8a4a1413b88dca5a8fa931824ee9c284e6\nExpose logo recognition API proto for GA.\n\nPiperOrigin-RevId: 299971671\n\n1c9fc2c9e03dadf15f16b1c4f570955bdcebe00e\nAdding ruby_package option to accessapproval.proto for the Ruby client libraries generation.\n\nPiperOrigin-RevId: 299955924\n\n1cc6f0a7bfb147e6f2ede911d9b01e7a9923b719\nbuild(google/maps/routes): generate api clients\n\nPiperOrigin-RevId: 299955905\n\n29a47c965aac79e3fe8e3314482ca0b5967680f0\nIncrease timeout to 1hr for method `dropRange` in bigtable/admin/v2, which is\nsynced with the timeout setting in gapic_yaml.\n\nPiperOrigin-RevId: 299917154\n\n8f631c4c70a60a9c7da3749511ee4ad432b62898\nbuild(google/maps/roads/v1op): move go to monorepo pattern\n\nPiperOrigin-RevId: 299885195\n\nd66816518844ebbf63504c9e8dfc7133921dd2cd\nbuild(google/maps/roads/v1op): Add bazel build files to generate clients.\n\nPiperOrigin-RevId: 299851148\n\naf7dff701fabe029672168649c62356cf1bb43d0\nAdd LogPlayerReports and LogImpressions to Playable Locations service\n\nPiperOrigin-RevId: 299724050\n\nb6927fca808f38df32a642c560082f5bf6538ced\nUpdate BigQuery Connection API v1beta1 proto: added credential to CloudSqlProperties.\n\nPiperOrigin-RevId: 299503150\n\n91e1fb5ef9829c0c7a64bfa5bde330e6ed594378\nchore: update protobuf (protoc) version to 3.11.2\n\nPiperOrigin-RevId: 299404145\n\n30e36b4bee6749c4799f4fc1a51cc8f058ba167d\nUpdate cloud asset api v1p4beta1.\n\nPiperOrigin-RevId: 299399890\n\nffbb493674099f265693872ae250711b2238090c\nfeat: cloudbuild/v1 add new fields and annotate OUTPUT_OUT fields.\n\nPiperOrigin-RevId: 299397780\n\nbc973a15818e00c19e121959832676e9b7607456\nbazel: Fix broken common dependency\n\nPiperOrigin-RevId: 299397431\n\n71094a343e3b962e744aa49eb9338219537474e4\nchore: bigtable/admin/v2 publish retry config\n\nPiperOrigin-RevId: 299391875\n\n8f488efd7bda33885cb674ddd023b3678c40bd82\nfeat: Migrate logging to GAPIC v2; release new features.\n\nIMPORTANT: This is a breaking change for client libraries\nin all languages.\n\nCommitter: @lukesneeringer, @jskeet\nPiperOrigin-RevId: 299370279\n\n007605bf9ad3a1fd775014ebefbf7f1e6b31ee71\nUpdate API for bigqueryreservation v1beta1.\n- Adds flex capacity commitment plan to CapacityCommitment.\n- Adds methods for getting and updating BiReservations.\n- Adds methods for updating/splitting/merging CapacityCommitments.\n\nPiperOrigin-RevId: 299368059\n\n" - } - }, - { - "git": { - "name": "synthtool", - "remote": "https://github.com/googleapis/synthtool.git", - "sha": "7e98e1609c91082f4eeb63b530c6468aefd18cfd" - } - } - ], + "updateTime": "2020-03-31T20:14:27.117117Z", "destinations": [ { "client": { diff --git a/system-test/fixtures/sample/src/index.ts b/system-test/fixtures/sample/src/index.ts index 9cb255e6..8ef08d3c 100644 --- a/system-test/fixtures/sample/src/index.ts +++ b/system-test/fixtures/sample/src/index.ts @@ -19,7 +19,7 @@ import {TranslationServiceClient} from '@google-cloud/translate'; function main() { - const translationServiceClient = new TranslationServiceClient(); + new TranslationServiceClient(); } main(); diff --git a/system-test/translate.ts b/system-test/translate.ts index fbff7119..561112ba 100644 --- a/system-test/translate.ts +++ b/system-test/translate.ts @@ -16,6 +16,7 @@ import * as assert from 'assert'; import {describe, it} from 'mocha'; import {TranslationServiceClient} from '../src'; +// eslint-disable-next-line @typescript-eslint/no-var-requires const http2spy = require('http2spy'); const API_KEY = process.env.TRANSLATE_API_KEY; @@ -137,9 +138,11 @@ describe('translate', () => { }); it('should populate x-goog-user-project header, and succeed if valid project', async () => { + // eslint-disable-next-line @typescript-eslint/no-var-requires const {GoogleAuth} = require('google-auth-library'); const auth = new GoogleAuth({ credentials: Object.assign( + // eslint-disable-next-line @typescript-eslint/no-var-requires require(process.env.GOOGLE_APPLICATION_CREDENTIALS || ''), { quota_project_id: process.env.GCLOUD_PROJECT, @@ -171,9 +174,11 @@ describe('translate', () => { }); it('should populate x-goog-user-project header, and fail if invalid project', async () => { + // eslint-disable-next-line @typescript-eslint/no-var-requires const {GoogleAuth} = require('google-auth-library'); const auth = new GoogleAuth({ credentials: Object.assign( + // eslint-disable-next-line @typescript-eslint/no-var-requires require(process.env.GOOGLE_APPLICATION_CREDENTIALS || ''), { quota_project_id: 'my-fake-billing-project', diff --git a/test/gapic-translation_service-v3.ts b/test/gapic-translation_service-v3.ts deleted file mode 100644 index 7e703356..00000000 --- a/test/gapic-translation_service-v3.ts +++ /dev/null @@ -1,595 +0,0 @@ -// Copyright 2020 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'; -import {describe, it} from 'mocha'; -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('v3.TranslationServiceClient', () => { - it('has servicePath', () => { - const servicePath = - translationserviceModule.v3.TranslationServiceClient.servicePath; - assert(servicePath); - }); - it('has apiEndpoint', () => { - const apiEndpoint = - translationserviceModule.v3.TranslationServiceClient.apiEndpoint; - assert(apiEndpoint); - }); - it('has port', () => { - const port = translationserviceModule.v3.TranslationServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - it('should create a client with no option', () => { - const client = new translationserviceModule.v3.TranslationServiceClient(); - assert(client); - }); - it('should create a client with gRPC fallback', () => { - const client = new translationserviceModule.v3.TranslationServiceClient({ - fallback: true, - }); - assert(client); - }); - it('has initialize method and supports deferred initialization', async () => { - const client = new translationserviceModule.v3.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - assert.strictEqual(client.translationServiceStub, undefined); - await client.initialize(); - assert(client.translationServiceStub); - }); - it('has close method', () => { - const client = new translationserviceModule.v3.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - client.close(); - }); - describe('translateText', () => { - it('invokes translateText without error', done => { - const client = new translationserviceModule.v3.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3.ITranslateTextRequest = {}; - request.parent = ''; - // 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.v3.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3.ITranslateTextRequest = {}; - request.parent = ''; - // 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.v3.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3.IDetectLanguageRequest = {}; - request.parent = ''; - // 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.v3.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3.IDetectLanguageRequest = {}; - request.parent = ''; - // 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.v3.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3.IGetSupportedLanguagesRequest = {}; - request.parent = ''; - // 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.v3.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3.IGetSupportedLanguagesRequest = {}; - request.parent = ''; - // 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.v3.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3.IGetGlossaryRequest = {}; - request.name = ''; - // 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.v3.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3.IGetGlossaryRequest = {}; - request.name = ''; - // 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.v3.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3.IBatchTranslateTextRequest = {}; - request.parent = ''; - // 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.v3.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3.IBatchTranslateTextRequest = {}; - request.parent = ''; - // 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.v3.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3.ICreateGlossaryRequest = {}; - request.parent = ''; - // 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.v3.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3.ICreateGlossaryRequest = {}; - request.parent = ''; - // 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.v3.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3.IDeleteGlossaryRequest = {}; - request.name = ''; - // 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.v3.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3.IDeleteGlossaryRequest = {}; - request.name = ''; - // 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.v3.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3.IListGlossariesRequest = {}; - request.parent = ''; - // 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.v3.TranslationServiceClient({ - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - }); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3.IListGlossariesRequest = {}; - request.parent = ''; - // Mock response - const expectedResponse = {response: 'data'}; - // 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(expectedResponse); - }); - }); -}); diff --git a/test/gapic-translation_service-v3beta1.ts b/test/gapic-translation_service-v3beta1.ts deleted file mode 100644 index fc38ef83..00000000 --- a/test/gapic-translation_service-v3beta1.ts +++ /dev/null @@ -1,633 +0,0 @@ -// Copyright 2020 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'; -import {describe, it} from 'mocha'; -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('v3beta1.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 fallback', () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient( - { - fallback: true, - } - ); - assert(client); - }); - it('has initialize method and supports deferred initialization', async () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient( - { - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - } - ); - assert.strictEqual(client.translationServiceStub, undefined); - await client.initialize(); - assert(client.translationServiceStub); - }); - it('has close method', () => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient( - { - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - } - ); - client.close(); - }); - describe('translateText', () => { - it('invokes translateText without error', done => { - const client = new translationserviceModule.v3beta1.TranslationServiceClient( - { - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - } - ); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3beta1.ITranslateTextRequest = {}; - request.parent = ''; - // 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', - } - ); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3beta1.ITranslateTextRequest = {}; - request.parent = ''; - // 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', - } - ); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3beta1.IDetectLanguageRequest = {}; - request.parent = ''; - // 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', - } - ); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3beta1.IDetectLanguageRequest = {}; - request.parent = ''; - // 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', - } - ); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest = {}; - request.parent = ''; - // 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', - } - ); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3beta1.IGetSupportedLanguagesRequest = {}; - request.parent = ''; - // 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', - } - ); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3beta1.IGetGlossaryRequest = {}; - request.name = ''; - // 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', - } - ); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3beta1.IGetGlossaryRequest = {}; - request.name = ''; - // 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', - } - ); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3beta1.IBatchTranslateTextRequest = {}; - request.parent = ''; - // 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', - } - ); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3beta1.IBatchTranslateTextRequest = {}; - request.parent = ''; - // 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', - } - ); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3beta1.ICreateGlossaryRequest = {}; - request.parent = ''; - // 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', - } - ); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3beta1.ICreateGlossaryRequest = {}; - request.parent = ''; - // 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', - } - ); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryRequest = {}; - request.name = ''; - // 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', - } - ); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3beta1.IDeleteGlossaryRequest = {}; - request.name = ''; - // 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', - } - ); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3beta1.IListGlossariesRequest = {}; - request.parent = ''; - // 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', - } - ); - // Initialize client before mocking - client.initialize(); - // Mock request - const request: protosTypes.google.cloud.translation.v3beta1.IListGlossariesRequest = {}; - request.parent = ''; - // Mock response - const expectedResponse = {response: 'data'}; - // 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(expectedResponse); - }); - }); -}); diff --git a/test/gapic_translation_service_v3.ts b/test/gapic_translation_service_v3.ts new file mode 100644 index 00000000..ac652102 --- /dev/null +++ b/test/gapic_translation_service_v3.ts @@ -0,0 +1,1598 @@ +// Copyright 2020 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 protos from '../protos/protos'; +import * as assert from 'assert'; +import * as sinon from 'sinon'; +import {SinonStub} from 'sinon'; +import {describe, it} from 'mocha'; +import * as translationserviceModule from '../src'; + +import {PassThrough} from 'stream'; + +import {protobuf, LROperation} from 'google-gax'; + +function generateSampleMessage(instance: T) { + const filledObject = (instance.constructor as typeof protobuf.Message).toObject( + instance as protobuf.Message, + {defaults: true} + ); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject + ) as T; +} + +function stubSimpleCall(response?: ResponseType, error?: Error) { + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); +} + +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); +} + +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); +} + +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); +} + +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); + } + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); + } + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); +} + +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({done: true, value: undefined}); + } + return Promise.resolve({done: false, value: responses![counter++]}); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); +} + +describe('v3.TranslationServiceClient', () => { + it('has servicePath', () => { + const servicePath = + translationserviceModule.v3.TranslationServiceClient.servicePath; + assert(servicePath); + }); + + it('has apiEndpoint', () => { + const apiEndpoint = + translationserviceModule.v3.TranslationServiceClient.apiEndpoint; + assert(apiEndpoint); + }); + + it('has port', () => { + const port = translationserviceModule.v3.TranslationServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); + + it('should create a client with no option', () => { + const client = new translationserviceModule.v3.TranslationServiceClient(); + assert(client); + }); + + it('should create a client with gRPC fallback', () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + fallback: true, + }); + assert(client); + }); + + it('has initialize method and supports deferred initialization', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + assert.strictEqual(client.translationServiceStub, undefined); + await client.initialize(); + assert(client.translationServiceStub); + }); + + it('has close method', () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.close(); + }); + + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); + + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + + describe('translateText', () => { + it('invokes translateText without error', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.TranslateTextRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3.TranslateTextResponse() + ); + client.innerApiCalls.translateText = stubSimpleCall(expectedResponse); + const [response] = await client.translateText(request); + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.translateText as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + + it('invokes translateText without error using callback', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.TranslateTextRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3.TranslateTextResponse() + ); + client.innerApiCalls.translateText = stubSimpleCallWithCallback( + expectedResponse + ); + const promise = new Promise((resolve, reject) => { + client.translateText( + request, + ( + err?: Error | null, + result?: protos.google.cloud.translation.v3.ITranslateTextResponse | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.translateText as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions /*, callback defined above */) + ); + }); + + it('invokes translateText with error', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.TranslateTextRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.innerApiCalls.translateText = stubSimpleCall( + undefined, + expectedError + ); + assert.rejects(async () => { + await client.translateText(request); + }, expectedError); + assert( + (client.innerApiCalls.translateText as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + }); + + describe('detectLanguage', () => { + it('invokes detectLanguage without error', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.DetectLanguageRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3.DetectLanguageResponse() + ); + client.innerApiCalls.detectLanguage = stubSimpleCall(expectedResponse); + const [response] = await client.detectLanguage(request); + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.detectLanguage as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + + it('invokes detectLanguage without error using callback', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.DetectLanguageRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3.DetectLanguageResponse() + ); + client.innerApiCalls.detectLanguage = stubSimpleCallWithCallback( + expectedResponse + ); + const promise = new Promise((resolve, reject) => { + client.detectLanguage( + request, + ( + err?: Error | null, + result?: protos.google.cloud.translation.v3.IDetectLanguageResponse | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.detectLanguage as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions /*, callback defined above */) + ); + }); + + it('invokes detectLanguage with error', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.DetectLanguageRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.innerApiCalls.detectLanguage = stubSimpleCall( + undefined, + expectedError + ); + assert.rejects(async () => { + await client.detectLanguage(request); + }, expectedError); + assert( + (client.innerApiCalls.detectLanguage as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + }); + + describe('getSupportedLanguages', () => { + it('invokes getSupportedLanguages without error', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.GetSupportedLanguagesRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3.SupportedLanguages() + ); + client.innerApiCalls.getSupportedLanguages = stubSimpleCall( + expectedResponse + ); + const [response] = await client.getSupportedLanguages(request); + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.getSupportedLanguages as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + + it('invokes getSupportedLanguages without error using callback', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.GetSupportedLanguagesRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3.SupportedLanguages() + ); + client.innerApiCalls.getSupportedLanguages = stubSimpleCallWithCallback( + expectedResponse + ); + const promise = new Promise((resolve, reject) => { + client.getSupportedLanguages( + request, + ( + err?: Error | null, + result?: protos.google.cloud.translation.v3.ISupportedLanguages | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.getSupportedLanguages as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions /*, callback defined above */) + ); + }); + + it('invokes getSupportedLanguages with error', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.GetSupportedLanguagesRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.innerApiCalls.getSupportedLanguages = stubSimpleCall( + undefined, + expectedError + ); + assert.rejects(async () => { + await client.getSupportedLanguages(request); + }, expectedError); + assert( + (client.innerApiCalls.getSupportedLanguages as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + }); + + describe('getGlossary', () => { + it('invokes getGlossary without error', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.GetGlossaryRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3.Glossary() + ); + client.innerApiCalls.getGlossary = stubSimpleCall(expectedResponse); + const [response] = await client.getGlossary(request); + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.getGlossary as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + + it('invokes getGlossary without error using callback', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.GetGlossaryRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3.Glossary() + ); + client.innerApiCalls.getGlossary = stubSimpleCallWithCallback( + expectedResponse + ); + const promise = new Promise((resolve, reject) => { + client.getGlossary( + request, + ( + err?: Error | null, + result?: protos.google.cloud.translation.v3.IGlossary | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.getGlossary as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions /*, callback defined above */) + ); + }); + + it('invokes getGlossary with error', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.GetGlossaryRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.innerApiCalls.getGlossary = stubSimpleCall( + undefined, + expectedError + ); + assert.rejects(async () => { + await client.getGlossary(request); + }, expectedError); + assert( + (client.innerApiCalls.getGlossary as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + }); + + describe('batchTranslateText', () => { + it('invokes batchTranslateText without error', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.BatchTranslateTextRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.batchTranslateText = stubLongRunningCall( + expectedResponse + ); + const [operation] = await client.batchTranslateText(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.batchTranslateText as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + + it('invokes batchTranslateText without error using callback', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.BatchTranslateTextRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.batchTranslateText = stubLongRunningCallWithCallback( + expectedResponse + ); + const promise = new Promise((resolve, reject) => { + client.batchTranslateText( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.translation.v3.IBatchTranslateResponse, + protos.google.cloud.translation.v3.IBatchTranslateMetadata + > | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.translation.v3.IBatchTranslateResponse, + protos.google.cloud.translation.v3.IBatchTranslateMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.batchTranslateText as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions /*, callback defined above */) + ); + }); + + it('invokes batchTranslateText with call error', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.BatchTranslateTextRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.innerApiCalls.batchTranslateText = stubLongRunningCall( + undefined, + expectedError + ); + assert.rejects(async () => { + await client.batchTranslateText(request); + }, expectedError); + assert( + (client.innerApiCalls.batchTranslateText as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + + it('invokes batchTranslateText with LRO error', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.BatchTranslateTextRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.innerApiCalls.batchTranslateText = stubLongRunningCall( + undefined, + undefined, + expectedError + ); + const [operation] = await client.batchTranslateText(request); + assert.rejects(async () => { + await operation.promise(); + }, expectedError); + assert( + (client.innerApiCalls.batchTranslateText as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + }); + + describe('createGlossary', () => { + it('invokes createGlossary without error', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.CreateGlossaryRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.createGlossary = stubLongRunningCall( + expectedResponse + ); + const [operation] = await client.createGlossary(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.createGlossary as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + + it('invokes createGlossary without error using callback', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.CreateGlossaryRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.createGlossary = stubLongRunningCallWithCallback( + expectedResponse + ); + const promise = new Promise((resolve, reject) => { + client.createGlossary( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.translation.v3.IGlossary, + protos.google.cloud.translation.v3.ICreateGlossaryMetadata + > | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.translation.v3.IGlossary, + protos.google.cloud.translation.v3.ICreateGlossaryMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.createGlossary as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions /*, callback defined above */) + ); + }); + + it('invokes createGlossary with call error', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.CreateGlossaryRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.innerApiCalls.createGlossary = stubLongRunningCall( + undefined, + expectedError + ); + assert.rejects(async () => { + await client.createGlossary(request); + }, expectedError); + assert( + (client.innerApiCalls.createGlossary as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + + it('invokes createGlossary with LRO error', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.CreateGlossaryRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.innerApiCalls.createGlossary = stubLongRunningCall( + undefined, + undefined, + expectedError + ); + const [operation] = await client.createGlossary(request); + assert.rejects(async () => { + await operation.promise(); + }, expectedError); + assert( + (client.innerApiCalls.createGlossary as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + }); + + describe('deleteGlossary', () => { + it('invokes deleteGlossary without error', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.DeleteGlossaryRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.deleteGlossary = stubLongRunningCall( + expectedResponse + ); + const [operation] = await client.deleteGlossary(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.deleteGlossary as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + + it('invokes deleteGlossary without error using callback', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.DeleteGlossaryRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.deleteGlossary = stubLongRunningCallWithCallback( + expectedResponse + ); + const promise = new Promise((resolve, reject) => { + client.deleteGlossary( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.translation.v3.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3.IDeleteGlossaryMetadata + > | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.translation.v3.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3.IDeleteGlossaryMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.deleteGlossary as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions /*, callback defined above */) + ); + }); + + it('invokes deleteGlossary with call error', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.DeleteGlossaryRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteGlossary = stubLongRunningCall( + undefined, + expectedError + ); + assert.rejects(async () => { + await client.deleteGlossary(request); + }, expectedError); + assert( + (client.innerApiCalls.deleteGlossary as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + + it('invokes deleteGlossary with LRO error', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.DeleteGlossaryRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteGlossary = stubLongRunningCall( + undefined, + undefined, + expectedError + ); + const [operation] = await client.deleteGlossary(request); + assert.rejects(async () => { + await operation.promise(); + }, expectedError); + assert( + (client.innerApiCalls.deleteGlossary as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + }); + + describe('listGlossaries', () => { + it('invokes listGlossaries without error', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.ListGlossariesRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.translation.v3.Glossary() + ), + generateSampleMessage( + new protos.google.cloud.translation.v3.Glossary() + ), + generateSampleMessage( + new protos.google.cloud.translation.v3.Glossary() + ), + ]; + client.innerApiCalls.listGlossaries = stubSimpleCall(expectedResponse); + const [response] = await client.listGlossaries(request); + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.listGlossaries as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + + it('invokes listGlossaries without error using callback', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.ListGlossariesRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.translation.v3.Glossary() + ), + generateSampleMessage( + new protos.google.cloud.translation.v3.Glossary() + ), + generateSampleMessage( + new protos.google.cloud.translation.v3.Glossary() + ), + ]; + client.innerApiCalls.listGlossaries = stubSimpleCallWithCallback( + expectedResponse + ); + const promise = new Promise((resolve, reject) => { + client.listGlossaries( + request, + ( + err?: Error | null, + result?: protos.google.cloud.translation.v3.IGlossary[] | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.listGlossaries as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions /*, callback defined above */) + ); + }); + + it('invokes listGlossaries with error', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.ListGlossariesRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.innerApiCalls.listGlossaries = stubSimpleCall( + undefined, + expectedError + ); + assert.rejects(async () => { + await client.listGlossaries(request); + }, expectedError); + assert( + (client.innerApiCalls.listGlossaries as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + + it('invokes listGlossariesStream without error', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.ListGlossariesRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.translation.v3.Glossary() + ), + generateSampleMessage( + new protos.google.cloud.translation.v3.Glossary() + ), + generateSampleMessage( + new protos.google.cloud.translation.v3.Glossary() + ), + ]; + client.descriptors.page.listGlossaries.createStream = stubPageStreamingCall( + expectedResponse + ); + const stream = client.listGlossariesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.translation.v3.Glossary[] = []; + stream.on( + 'data', + (response: protos.google.cloud.translation.v3.Glossary) => { + responses.push(response); + } + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listGlossaries.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listGlossaries, request) + ); + assert.strictEqual( + (client.descriptors.page.listGlossaries + .createStream as SinonStub).getCall(0).args[2].otherArgs.headers[ + 'x-goog-request-params' + ], + expectedHeaderRequestParams + ); + }); + + it('invokes listGlossariesStream with error', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.ListGlossariesRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedError = new Error('expected'); + client.descriptors.page.listGlossaries.createStream = stubPageStreamingCall( + undefined, + expectedError + ); + const stream = client.listGlossariesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.translation.v3.Glossary[] = []; + stream.on( + 'data', + (response: protos.google.cloud.translation.v3.Glossary) => { + responses.push(response); + } + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + assert.rejects(async () => { + await promise; + }, expectedError); + assert( + (client.descriptors.page.listGlossaries.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listGlossaries, request) + ); + assert.strictEqual( + (client.descriptors.page.listGlossaries + .createStream as SinonStub).getCall(0).args[2].otherArgs.headers[ + 'x-goog-request-params' + ], + expectedHeaderRequestParams + ); + }); + + it('uses async iteration with listGlossaries without error', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.ListGlossariesRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.translation.v3.Glossary() + ), + generateSampleMessage( + new protos.google.cloud.translation.v3.Glossary() + ), + generateSampleMessage( + new protos.google.cloud.translation.v3.Glossary() + ), + ]; + client.descriptors.page.listGlossaries.asyncIterate = stubAsyncIterationCall( + expectedResponse + ); + const responses: protos.google.cloud.translation.v3.IGlossary[] = []; + const iterable = client.listGlossariesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listGlossaries + .asyncIterate as SinonStub).getCall(0).args[1], + request + ); + assert.strictEqual( + (client.descriptors.page.listGlossaries + .asyncIterate as SinonStub).getCall(0).args[2].otherArgs.headers[ + 'x-goog-request-params' + ], + expectedHeaderRequestParams + ); + }); + + it('uses async iteration with listGlossaries with error', async () => { + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3.ListGlossariesRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedError = new Error('expected'); + client.descriptors.page.listGlossaries.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError + ); + const iterable = client.listGlossariesAsync(request); + assert.rejects(async () => { + const responses: protos.google.cloud.translation.v3.IGlossary[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listGlossaries + .asyncIterate as SinonStub).getCall(0).args[1], + request + ); + assert.strictEqual( + (client.descriptors.page.listGlossaries + .asyncIterate as SinonStub).getCall(0).args[2].otherArgs.headers[ + 'x-goog-request-params' + ], + expectedHeaderRequestParams + ); + }); + }); + + describe('Path templates', () => { + describe('glossary', () => { + const fakePath = '/rendered/path/glossary'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + glossary: 'glossaryValue', + }; + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + client.pathTemplates.glossaryPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.glossaryPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('glossaryPath', () => { + const result = client.glossaryPath( + 'projectValue', + 'locationValue', + 'glossaryValue' + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.glossaryPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters) + ); + }); + + it('matchProjectFromGlossaryName', () => { + const result = client.matchProjectFromGlossaryName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.glossaryPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + + it('matchLocationFromGlossaryName', () => { + const result = client.matchLocationFromGlossaryName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.glossaryPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + + it('matchGlossaryFromGlossaryName', () => { + const result = client.matchGlossaryFromGlossaryName(fakePath); + assert.strictEqual(result, 'glossaryValue'); + assert( + (client.pathTemplates.glossaryPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + }); + + describe('location', () => { + const fakePath = '/rendered/path/location'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + }; + const client = new translationserviceModule.v3.TranslationServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + client.initialize(); + client.pathTemplates.locationPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.locationPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('locationPath', () => { + const result = client.locationPath('projectValue', 'locationValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.locationPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters) + ); + }); + + it('matchProjectFromLocationName', () => { + const result = client.matchProjectFromLocationName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.locationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + + it('matchLocationFromLocationName', () => { + const result = client.matchLocationFromLocationName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.locationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + }); + }); +}); diff --git a/test/gapic_translation_service_v3beta1.ts b/test/gapic_translation_service_v3beta1.ts new file mode 100644 index 00000000..03e054de --- /dev/null +++ b/test/gapic_translation_service_v3beta1.ts @@ -0,0 +1,1674 @@ +// Copyright 2020 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 protos from '../protos/protos'; +import * as assert from 'assert'; +import * as sinon from 'sinon'; +import {SinonStub} from 'sinon'; +import {describe, it} from 'mocha'; +import * as translationserviceModule from '../src'; + +import {PassThrough} from 'stream'; + +import {protobuf, LROperation} from 'google-gax'; + +function generateSampleMessage(instance: T) { + const filledObject = (instance.constructor as typeof protobuf.Message).toObject( + instance as protobuf.Message, + {defaults: true} + ); + return (instance.constructor as typeof protobuf.Message).fromObject( + filledObject + ) as T; +} + +function stubSimpleCall(response?: ResponseType, error?: Error) { + return error + ? sinon.stub().rejects(error) + : sinon.stub().resolves([response]); +} + +function stubSimpleCallWithCallback( + response?: ResponseType, + error?: Error +) { + return error + ? sinon.stub().callsArgWith(2, error) + : sinon.stub().callsArgWith(2, null, response); +} + +function stubLongRunningCall( + response?: ResponseType, + callError?: Error, + lroError?: Error +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().rejects(callError) + : sinon.stub().resolves([mockOperation]); +} + +function stubLongRunningCallWithCallback( + response?: ResponseType, + callError?: Error, + lroError?: Error +) { + const innerStub = lroError + ? sinon.stub().rejects(lroError) + : sinon.stub().resolves([response]); + const mockOperation = { + promise: innerStub, + }; + return callError + ? sinon.stub().callsArgWith(2, callError) + : sinon.stub().callsArgWith(2, null, mockOperation); +} + +function stubPageStreamingCall( + responses?: ResponseType[], + error?: Error +) { + const pagingStub = sinon.stub(); + if (responses) { + for (let i = 0; i < responses.length; ++i) { + pagingStub.onCall(i).callsArgWith(2, null, responses[i]); + } + } + const transformStub = error + ? sinon.stub().callsArgWith(2, error) + : pagingStub; + const mockStream = new PassThrough({ + objectMode: true, + transform: transformStub, + }); + // trigger as many responses as needed + if (responses) { + for (let i = 0; i < responses.length; ++i) { + setImmediate(() => { + mockStream.write({}); + }); + } + setImmediate(() => { + mockStream.end(); + }); + } else { + setImmediate(() => { + mockStream.write({}); + }); + setImmediate(() => { + mockStream.end(); + }); + } + return sinon.stub().returns(mockStream); +} + +function stubAsyncIterationCall( + responses?: ResponseType[], + error?: Error +) { + let counter = 0; + const asyncIterable = { + [Symbol.asyncIterator]() { + return { + async next() { + if (error) { + return Promise.reject(error); + } + if (counter >= responses!.length) { + return Promise.resolve({done: true, value: undefined}); + } + return Promise.resolve({done: false, value: responses![counter++]}); + }, + }; + }, + }; + return sinon.stub().returns(asyncIterable); +} + +describe('v3beta1.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 fallback', () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + fallback: true, + } + ); + assert(client); + }); + + it('has initialize method and supports deferred initialization', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + assert.strictEqual(client.translationServiceStub, undefined); + await client.initialize(); + assert(client.translationServiceStub); + }); + + it('has close method', () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.close(); + }); + + it('has getProjectId method', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.auth.getProjectId = sinon.stub().resolves(fakeProjectId); + const result = await client.getProjectId(); + assert.strictEqual(result, fakeProjectId); + assert((client.auth.getProjectId as SinonStub).calledWithExactly()); + }); + + it('has getProjectId method with callback', async () => { + const fakeProjectId = 'fake-project-id'; + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.auth.getProjectId = sinon + .stub() + .callsArgWith(0, null, fakeProjectId); + const promise = new Promise((resolve, reject) => { + client.getProjectId((err?: Error | null, projectId?: string | null) => { + if (err) { + reject(err); + } else { + resolve(projectId); + } + }); + }); + const result = await promise; + assert.strictEqual(result, fakeProjectId); + }); + + describe('translateText', () => { + it('invokes translateText without error', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.TranslateTextRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.TranslateTextResponse() + ); + client.innerApiCalls.translateText = stubSimpleCall(expectedResponse); + const [response] = await client.translateText(request); + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.translateText as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + + it('invokes translateText without error using callback', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.TranslateTextRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.TranslateTextResponse() + ); + client.innerApiCalls.translateText = stubSimpleCallWithCallback( + expectedResponse + ); + const promise = new Promise((resolve, reject) => { + client.translateText( + request, + ( + err?: Error | null, + result?: protos.google.cloud.translation.v3beta1.ITranslateTextResponse | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.translateText as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions /*, callback defined above */) + ); + }); + + it('invokes translateText with error', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.TranslateTextRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.innerApiCalls.translateText = stubSimpleCall( + undefined, + expectedError + ); + assert.rejects(async () => { + await client.translateText(request); + }, expectedError); + assert( + (client.innerApiCalls.translateText as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + }); + + describe('detectLanguage', () => { + it('invokes detectLanguage without error', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DetectLanguageRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DetectLanguageResponse() + ); + client.innerApiCalls.detectLanguage = stubSimpleCall(expectedResponse); + const [response] = await client.detectLanguage(request); + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.detectLanguage as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + + it('invokes detectLanguage without error using callback', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DetectLanguageRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DetectLanguageResponse() + ); + client.innerApiCalls.detectLanguage = stubSimpleCallWithCallback( + expectedResponse + ); + const promise = new Promise((resolve, reject) => { + client.detectLanguage( + request, + ( + err?: Error | null, + result?: protos.google.cloud.translation.v3beta1.IDetectLanguageResponse | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.detectLanguage as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions /*, callback defined above */) + ); + }); + + it('invokes detectLanguage with error', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DetectLanguageRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.innerApiCalls.detectLanguage = stubSimpleCall( + undefined, + expectedError + ); + assert.rejects(async () => { + await client.detectLanguage(request); + }, expectedError); + assert( + (client.innerApiCalls.detectLanguage as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + }); + + describe('getSupportedLanguages', () => { + it('invokes getSupportedLanguages without error', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.SupportedLanguages() + ); + client.innerApiCalls.getSupportedLanguages = stubSimpleCall( + expectedResponse + ); + const [response] = await client.getSupportedLanguages(request); + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.getSupportedLanguages as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + + it('invokes getSupportedLanguages without error using callback', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.SupportedLanguages() + ); + client.innerApiCalls.getSupportedLanguages = stubSimpleCallWithCallback( + expectedResponse + ); + const promise = new Promise((resolve, reject) => { + client.getSupportedLanguages( + request, + ( + err?: Error | null, + result?: protos.google.cloud.translation.v3beta1.ISupportedLanguages | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.getSupportedLanguages as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions /*, callback defined above */) + ); + }); + + it('invokes getSupportedLanguages with error', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.GetSupportedLanguagesRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.innerApiCalls.getSupportedLanguages = stubSimpleCall( + undefined, + expectedError + ); + assert.rejects(async () => { + await client.getSupportedLanguages(request); + }, expectedError); + assert( + (client.innerApiCalls.getSupportedLanguages as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + }); + + describe('getGlossary', () => { + it('invokes getGlossary without error', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.GetGlossaryRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary() + ); + client.innerApiCalls.getGlossary = stubSimpleCall(expectedResponse); + const [response] = await client.getGlossary(request); + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.getGlossary as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + + it('invokes getGlossary without error using callback', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.GetGlossaryRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary() + ); + client.innerApiCalls.getGlossary = stubSimpleCallWithCallback( + expectedResponse + ); + const promise = new Promise((resolve, reject) => { + client.getGlossary( + request, + ( + err?: Error | null, + result?: protos.google.cloud.translation.v3beta1.IGlossary | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.getGlossary as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions /*, callback defined above */) + ); + }); + + it('invokes getGlossary with error', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.GetGlossaryRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.innerApiCalls.getGlossary = stubSimpleCall( + undefined, + expectedError + ); + assert.rejects(async () => { + await client.getGlossary(request); + }, expectedError); + assert( + (client.innerApiCalls.getGlossary as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + }); + + describe('batchTranslateText', () => { + it('invokes batchTranslateText without error', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.BatchTranslateTextRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.batchTranslateText = stubLongRunningCall( + expectedResponse + ); + const [operation] = await client.batchTranslateText(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.batchTranslateText as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + + it('invokes batchTranslateText without error using callback', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.BatchTranslateTextRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.batchTranslateText = stubLongRunningCallWithCallback( + expectedResponse + ); + const promise = new Promise((resolve, reject) => { + client.batchTranslateText( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata + > | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.translation.v3beta1.IBatchTranslateResponse, + protos.google.cloud.translation.v3beta1.IBatchTranslateMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.batchTranslateText as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions /*, callback defined above */) + ); + }); + + it('invokes batchTranslateText with call error', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.BatchTranslateTextRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.innerApiCalls.batchTranslateText = stubLongRunningCall( + undefined, + expectedError + ); + assert.rejects(async () => { + await client.batchTranslateText(request); + }, expectedError); + assert( + (client.innerApiCalls.batchTranslateText as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + + it('invokes batchTranslateText with LRO error', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.BatchTranslateTextRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.innerApiCalls.batchTranslateText = stubLongRunningCall( + undefined, + undefined, + expectedError + ); + const [operation] = await client.batchTranslateText(request); + assert.rejects(async () => { + await operation.promise(); + }, expectedError); + assert( + (client.innerApiCalls.batchTranslateText as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + }); + + describe('createGlossary', () => { + it('invokes createGlossary without error', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.CreateGlossaryRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.createGlossary = stubLongRunningCall( + expectedResponse + ); + const [operation] = await client.createGlossary(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.createGlossary as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + + it('invokes createGlossary without error using callback', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.CreateGlossaryRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.createGlossary = stubLongRunningCallWithCallback( + expectedResponse + ); + const promise = new Promise((resolve, reject) => { + client.createGlossary( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + > | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.translation.v3beta1.IGlossary, + protos.google.cloud.translation.v3beta1.ICreateGlossaryMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.createGlossary as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions /*, callback defined above */) + ); + }); + + it('invokes createGlossary with call error', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.CreateGlossaryRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.innerApiCalls.createGlossary = stubLongRunningCall( + undefined, + expectedError + ); + assert.rejects(async () => { + await client.createGlossary(request); + }, expectedError); + assert( + (client.innerApiCalls.createGlossary as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + + it('invokes createGlossary with LRO error', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.CreateGlossaryRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.innerApiCalls.createGlossary = stubLongRunningCall( + undefined, + undefined, + expectedError + ); + const [operation] = await client.createGlossary(request); + assert.rejects(async () => { + await operation.promise(); + }, expectedError); + assert( + (client.innerApiCalls.createGlossary as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + }); + + describe('deleteGlossary', () => { + it('invokes deleteGlossary without error', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DeleteGlossaryRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.deleteGlossary = stubLongRunningCall( + expectedResponse + ); + const [operation] = await client.deleteGlossary(request); + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.deleteGlossary as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + + it('invokes deleteGlossary without error using callback', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DeleteGlossaryRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = generateSampleMessage( + new protos.google.longrunning.Operation() + ); + client.innerApiCalls.deleteGlossary = stubLongRunningCallWithCallback( + expectedResponse + ); + const promise = new Promise((resolve, reject) => { + client.deleteGlossary( + request, + ( + err?: Error | null, + result?: LROperation< + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + > | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const operation = (await promise) as LROperation< + protos.google.cloud.translation.v3beta1.IDeleteGlossaryResponse, + protos.google.cloud.translation.v3beta1.IDeleteGlossaryMetadata + >; + const [response] = await operation.promise(); + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.deleteGlossary as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions /*, callback defined above */) + ); + }); + + it('invokes deleteGlossary with call error', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DeleteGlossaryRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteGlossary = stubLongRunningCall( + undefined, + expectedError + ); + assert.rejects(async () => { + await client.deleteGlossary(request); + }, expectedError); + assert( + (client.innerApiCalls.deleteGlossary as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + + it('invokes deleteGlossary with LRO error', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.DeleteGlossaryRequest() + ); + request.name = ''; + const expectedHeaderRequestParams = 'name='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.innerApiCalls.deleteGlossary = stubLongRunningCall( + undefined, + undefined, + expectedError + ); + const [operation] = await client.deleteGlossary(request); + assert.rejects(async () => { + await operation.promise(); + }, expectedError); + assert( + (client.innerApiCalls.deleteGlossary as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + }); + + describe('listGlossaries', () => { + it('invokes listGlossaries without error', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.ListGlossariesRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary() + ), + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary() + ), + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary() + ), + ]; + client.innerApiCalls.listGlossaries = stubSimpleCall(expectedResponse); + const [response] = await client.listGlossaries(request); + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.listGlossaries as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + + it('invokes listGlossaries without error using callback', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.ListGlossariesRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary() + ), + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary() + ), + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary() + ), + ]; + client.innerApiCalls.listGlossaries = stubSimpleCallWithCallback( + expectedResponse + ); + const promise = new Promise((resolve, reject) => { + client.listGlossaries( + request, + ( + err?: Error | null, + result?: protos.google.cloud.translation.v3beta1.IGlossary[] | null + ) => { + if (err) { + reject(err); + } else { + resolve(result); + } + } + ); + }); + const response = await promise; + assert.deepStrictEqual(response, expectedResponse); + assert( + (client.innerApiCalls.listGlossaries as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions /*, callback defined above */) + ); + }); + + it('invokes listGlossaries with error', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.ListGlossariesRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedOptions = { + otherArgs: { + headers: { + 'x-goog-request-params': expectedHeaderRequestParams, + }, + }, + }; + const expectedError = new Error('expected'); + client.innerApiCalls.listGlossaries = stubSimpleCall( + undefined, + expectedError + ); + assert.rejects(async () => { + await client.listGlossaries(request); + }, expectedError); + assert( + (client.innerApiCalls.listGlossaries as SinonStub) + .getCall(0) + .calledWith(request, expectedOptions, undefined) + ); + }); + + it('invokes listGlossariesStream without error', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.ListGlossariesRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary() + ), + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary() + ), + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary() + ), + ]; + client.descriptors.page.listGlossaries.createStream = stubPageStreamingCall( + expectedResponse + ); + const stream = client.listGlossariesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.translation.v3beta1.Glossary[] = []; + stream.on( + 'data', + (response: protos.google.cloud.translation.v3beta1.Glossary) => { + responses.push(response); + } + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + const responses = await promise; + assert.deepStrictEqual(responses, expectedResponse); + assert( + (client.descriptors.page.listGlossaries.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listGlossaries, request) + ); + assert.strictEqual( + (client.descriptors.page.listGlossaries + .createStream as SinonStub).getCall(0).args[2].otherArgs.headers[ + 'x-goog-request-params' + ], + expectedHeaderRequestParams + ); + }); + + it('invokes listGlossariesStream with error', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.ListGlossariesRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedError = new Error('expected'); + client.descriptors.page.listGlossaries.createStream = stubPageStreamingCall( + undefined, + expectedError + ); + const stream = client.listGlossariesStream(request); + const promise = new Promise((resolve, reject) => { + const responses: protos.google.cloud.translation.v3beta1.Glossary[] = []; + stream.on( + 'data', + (response: protos.google.cloud.translation.v3beta1.Glossary) => { + responses.push(response); + } + ); + stream.on('end', () => { + resolve(responses); + }); + stream.on('error', (err: Error) => { + reject(err); + }); + }); + assert.rejects(async () => { + await promise; + }, expectedError); + assert( + (client.descriptors.page.listGlossaries.createStream as SinonStub) + .getCall(0) + .calledWith(client.innerApiCalls.listGlossaries, request) + ); + assert.strictEqual( + (client.descriptors.page.listGlossaries + .createStream as SinonStub).getCall(0).args[2].otherArgs.headers[ + 'x-goog-request-params' + ], + expectedHeaderRequestParams + ); + }); + + it('uses async iteration with listGlossaries without error', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.ListGlossariesRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedResponse = [ + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary() + ), + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary() + ), + generateSampleMessage( + new protos.google.cloud.translation.v3beta1.Glossary() + ), + ]; + client.descriptors.page.listGlossaries.asyncIterate = stubAsyncIterationCall( + expectedResponse + ); + const responses: protos.google.cloud.translation.v3beta1.IGlossary[] = []; + const iterable = client.listGlossariesAsync(request); + for await (const resource of iterable) { + responses.push(resource!); + } + assert.deepStrictEqual(responses, expectedResponse); + assert.deepStrictEqual( + (client.descriptors.page.listGlossaries + .asyncIterate as SinonStub).getCall(0).args[1], + request + ); + assert.strictEqual( + (client.descriptors.page.listGlossaries + .asyncIterate as SinonStub).getCall(0).args[2].otherArgs.headers[ + 'x-goog-request-params' + ], + expectedHeaderRequestParams + ); + }); + + it('uses async iteration with listGlossaries with error', async () => { + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + const request = generateSampleMessage( + new protos.google.cloud.translation.v3beta1.ListGlossariesRequest() + ); + request.parent = ''; + const expectedHeaderRequestParams = 'parent='; + const expectedError = new Error('expected'); + client.descriptors.page.listGlossaries.asyncIterate = stubAsyncIterationCall( + undefined, + expectedError + ); + const iterable = client.listGlossariesAsync(request); + assert.rejects(async () => { + const responses: protos.google.cloud.translation.v3beta1.IGlossary[] = []; + for await (const resource of iterable) { + responses.push(resource!); + } + }); + assert.deepStrictEqual( + (client.descriptors.page.listGlossaries + .asyncIterate as SinonStub).getCall(0).args[1], + request + ); + assert.strictEqual( + (client.descriptors.page.listGlossaries + .asyncIterate as SinonStub).getCall(0).args[2].otherArgs.headers[ + 'x-goog-request-params' + ], + expectedHeaderRequestParams + ); + }); + }); + + describe('Path templates', () => { + describe('glossary', () => { + const fakePath = '/rendered/path/glossary'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + glossary: 'glossaryValue', + }; + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + client.pathTemplates.glossaryPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.glossaryPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('glossaryPath', () => { + const result = client.glossaryPath( + 'projectValue', + 'locationValue', + 'glossaryValue' + ); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.glossaryPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters) + ); + }); + + it('matchProjectFromGlossaryName', () => { + const result = client.matchProjectFromGlossaryName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.glossaryPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + + it('matchLocationFromGlossaryName', () => { + const result = client.matchLocationFromGlossaryName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.glossaryPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + + it('matchGlossaryFromGlossaryName', () => { + const result = client.matchGlossaryFromGlossaryName(fakePath); + assert.strictEqual(result, 'glossaryValue'); + assert( + (client.pathTemplates.glossaryPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + }); + + describe('location', () => { + const fakePath = '/rendered/path/location'; + const expectedParameters = { + project: 'projectValue', + location: 'locationValue', + }; + const client = new translationserviceModule.v3beta1.TranslationServiceClient( + { + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + } + ); + client.initialize(); + client.pathTemplates.locationPathTemplate.render = sinon + .stub() + .returns(fakePath); + client.pathTemplates.locationPathTemplate.match = sinon + .stub() + .returns(expectedParameters); + + it('locationPath', () => { + const result = client.locationPath('projectValue', 'locationValue'); + assert.strictEqual(result, fakePath); + assert( + (client.pathTemplates.locationPathTemplate.render as SinonStub) + .getCall(-1) + .calledWith(expectedParameters) + ); + }); + + it('matchProjectFromLocationName', () => { + const result = client.matchProjectFromLocationName(fakePath); + assert.strictEqual(result, 'projectValue'); + assert( + (client.pathTemplates.locationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + + it('matchLocationFromLocationName', () => { + const result = client.matchLocationFromLocationName(fakePath); + assert.strictEqual(result, 'locationValue'); + assert( + (client.pathTemplates.locationPathTemplate.match as SinonStub) + .getCall(-1) + .calledWith(fakePath) + ); + }); + }); + }); +}); diff --git a/test/index.ts b/test/index.ts index 964ba950..194d2096 100644 --- a/test/index.ts +++ b/test/index.ts @@ -19,13 +19,14 @@ import { } from '@google-cloud/common/build/src/util'; import * as pfy from '@google-cloud/promisify'; import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import {after, afterEach, before, beforeEach, describe, it} from 'mocha'; import * as extend from 'extend'; import * as proxyquire from 'proxyquire'; import * as r from 'request'; import * as orig from '../src'; +// eslint-disable-next-line @typescript-eslint/no-var-requires const pkgJson = require('../../package.json'); // tslint:disable-next-line no-any @@ -57,6 +58,7 @@ class FakeService { calledWith_: IArguments; request?: Function; constructor() { + // eslint-disable-next-line prefer-rest-params this.calledWith_ = arguments; } }