From 8f342cdc94708b8b0e9a3240a07dd1676cb9357f Mon Sep 17 00:00:00 2001 From: Alexander Fenster Date: Wed, 4 Mar 2020 17:08:40 -0800 Subject: [PATCH] feat: deferred initialization --- .../big_query_storage_client.ts.baseline | 74 ++++++--- ...apic-big_query_storage-v1beta1.ts.baseline | 36 +++++ .../dlp/src/v2/dlp_service_client.ts.baseline | 129 ++++++++++++---- .../dlp/test/gapic-dlp_service-v2.ts.baseline | 140 ++++++++++++++++++ .../key_management_service_client.ts.baseline | 98 +++++++++--- ...apic-key_management_service-v1.ts.baseline | 108 ++++++++++++++ .../alert_policy_service_client.ts.baseline | 119 +++++++++------ .../src/v3/group_service_client.ts.baseline | 123 +++++++++------ .../src/v3/metric_service_client.ts.baseline | 140 +++++++++++------- ...ication_channel_service_client.ts.baseline | 127 ++++++++++------ ...vice_monitoring_service_client.ts.baseline | 127 ++++++++++------ .../uptime_check_service_client.ts.baseline | 123 +++++++++------ .../gapic-alert_policy_service-v3.ts.baseline | 36 +++++ .../test/gapic-group_service-v3.ts.baseline | 40 +++++ .../test/gapic-metric_service-v3.ts.baseline | 48 ++++++ ...otification_channel_service-v3.ts.baseline | 56 +++++++ ...-service_monitoring_service-v3.ts.baseline | 56 +++++++ .../gapic-uptime_check_service-v3.ts.baseline | 40 +++++ .../v1beta1/cloud_redis_client.ts.baseline | 98 ++++++++---- .../gapic-cloud_redis-v1beta1.ts.baseline | 48 ++++++ .../src/v1beta1/echo_client.ts.baseline | 105 ++++++++----- .../src/v1beta1/identity_client.ts.baseline | 85 +++++++---- .../src/v1beta1/messaging_client.ts.baseline | 115 +++++++++----- .../src/v1beta1/testing_client.ts.baseline | 91 ++++++++---- .../test/gapic-echo-v1beta1.ts.baseline | 40 +++++ .../test/gapic-identity-v1beta1.ts.baseline | 36 +++++ .../test/gapic-messaging-v1beta1.ts.baseline | 68 +++++++++ .../test/gapic-testing-v1beta1.ts.baseline | 48 ++++++ .../src/v1/text_to_speech_client.ts.baseline | 65 +++++--- .../test/gapic-text_to_speech-v1.ts.baseline | 24 +++ .../translation_service_client.ts.baseline | 92 ++++++++---- ...ic-translation_service-v3beta1.ts.baseline | 48 ++++++ .../src/$version/$service_client.ts.njk | 88 +++++++---- .../test/gapic-$service-$version.ts.njk | 36 +++++ 34 files changed, 2150 insertions(+), 557 deletions(-) diff --git a/baselines/bigquery-storage/src/v1beta1/big_query_storage_client.ts.baseline b/baselines/bigquery-storage/src/v1beta1/big_query_storage_client.ts.baseline index 878cdeb02..dea4863c4 100644 --- a/baselines/bigquery-storage/src/v1beta1/big_query_storage_client.ts.baseline +++ b/baselines/bigquery-storage/src/v1beta1/big_query_storage_client.ts.baseline @@ -37,8 +37,13 @@ export class BigQueryStorageClient { private _innerApiCalls: {[name: string]: Function}; private _pathTemplates: {[name: string]: gax.PathTemplate}; private _terminated = false; + private _opts: ClientOptions; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; auth: gax.GoogleAuth; - bigQueryStorageStub: Promise<{[name: string]: Function}>; + bigQueryStorageStub?: Promise<{[name: string]: Function}>; /** * Construct an instance of BigQueryStorageClient. @@ -91,28 +96,31 @@ export class BigQueryStorageClient { // If we are in browser, we are already using fallback because of the // "browser" field in package.json. // But if we were explicitly requested to use fallback, let's do it now. - const gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; + this._gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; // Create a `gaxGrpc` object, with any grpc-specific options // sent to the client. opts.scopes = (this.constructor as typeof BigQueryStorageClient).scopes; - const gaxGrpc = new gaxModule.GrpcClient(opts); + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (gaxGrpc.auth as gax.GoogleAuth); + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); // Determine the client header string. const clientHeader = [ - `gax/${gaxModule.version}`, + `gax/${this._gaxModule.version}`, `gapic/${version}`, ]; if (typeof process !== 'undefined' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { - clientHeader.push(`gl-web/${gaxModule.version}`); + clientHeader.push(`gl-web/${this._gaxModule.version}`); } if (!opts.fallback) { - clientHeader.push(`grpc/${gaxGrpc.grpcVersion}`); + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { clientHeader.push(`${opts.libName}/${opts.libVersion}`); @@ -122,7 +130,7 @@ export class BigQueryStorageClient { // For browsers, pass the JSON content. const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); - const protos = gaxGrpc.loadProto( + this._protos = this._gaxGrpc.loadProto( opts.fallback ? require("../../protos/protos.json") : nodejsProtoPath @@ -132,10 +140,10 @@ export class BigQueryStorageClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this._pathTemplates = { - readSessionPathTemplate: new gaxModule.PathTemplate( + readSessionPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/locations/{location}/sessions/{session}' ), - streamPathTemplate: new gaxModule.PathTemplate( + streamPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/locations/{location}/streams/{stream}' ), }; @@ -143,11 +151,11 @@ export class BigQueryStorageClient { // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this._descriptors.stream = { - readRows: new gaxModule.StreamDescriptor(gax.StreamType.SERVER_STREAMING) + readRows: new this._gaxModule.StreamDescriptor(gax.StreamType.SERVER_STREAMING) }; // Put together the default options sent with requests. - const defaults = gaxGrpc.constructSettings( + this._defaults = this._gaxGrpc.constructSettings( 'google.cloud.bigquery.storage.v1beta1.BigQueryStorage', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); @@ -155,15 +163,33 @@ export class BigQueryStorageClient { // of calling the API is handled in `google-gax`, with this code // merely providing the destination and request information. this._innerApiCalls = {}; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.bigQueryStorageStub) { + return this.bigQueryStorageStub; + } // Put together the "service stub" for // google.cloud.bigquery.storage.v1beta1.BigQueryStorage. - this.bigQueryStorageStub = gaxGrpc.createStub( - opts.fallback ? - (protos as protobuf.Root).lookupService('google.cloud.bigquery.storage.v1beta1.BigQueryStorage') : + this.bigQueryStorageStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.cloud.bigquery.storage.v1beta1.BigQueryStorage') : // tslint:disable-next-line no-any - (protos as any).google.cloud.bigquery.storage.v1beta1.BigQueryStorage, - opts) as Promise<{[method: string]: Function}>; + (this._protos as any).google.cloud.bigquery.storage.v1beta1.BigQueryStorage, + this._opts) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -182,9 +208,9 @@ export class BigQueryStorageClient { throw err; }); - const apiCall = gaxModule.createApiCall( + const apiCall = this._gaxModule.createApiCall( innerCallPromise, - defaults[methodName], + this._defaults[methodName], this._descriptors.page[methodName] || this._descriptors.stream[methodName] || this._descriptors.longrunning[methodName] @@ -198,6 +224,8 @@ export class BigQueryStorageClient { return apiCall(argument, callOptions, callback); }; } + + return this.bigQueryStorageStub; } /** @@ -343,6 +371,7 @@ export class BigQueryStorageClient { 'table_reference.project_id': request.tableReference!.projectId || '', 'table_reference.dataset_id': request.tableReference!.datasetId || '', }); + this.initialize(); return this._innerApiCalls.createReadSession(request, options, callback); } batchCreateReadSessionStreams( @@ -409,6 +438,7 @@ export class BigQueryStorageClient { ] = gax.routingHeader.fromParams({ 'session.name': request.session!.name || '', }); + this.initialize(); return this._innerApiCalls.batchCreateReadSessionStreams(request, options, callback); } finalizeStream( @@ -481,6 +511,7 @@ export class BigQueryStorageClient { ] = gax.routingHeader.fromParams({ 'stream.name': request.stream!.name || '', }); + this.initialize(); return this._innerApiCalls.finalizeStream(request, options, callback); } splitReadStream( @@ -560,6 +591,7 @@ export class BigQueryStorageClient { ] = gax.routingHeader.fromParams({ 'original_stream.name': request.originalStream!.name || '', }); + this.initialize(); return this._innerApiCalls.splitReadStream(request, options, callback); } @@ -598,6 +630,7 @@ export class BigQueryStorageClient { ] = gax.routingHeader.fromParams({ 'read_position.stream.name': request.readPosition!.stream!.name || '', }); + this.initialize(); return this._innerApiCalls.readRows(request, options); } @@ -709,8 +742,9 @@ export class BigQueryStorageClient { * The client will no longer be usable and all future behavior is undefined. */ close(): Promise { + this.initialize(); if (!this._terminated) { - return this.bigQueryStorageStub.then(stub => { + return this.bigQueryStorageStub!.then(stub => { this._terminated = true; stub.close(); }); diff --git a/baselines/bigquery-storage/test/gapic-big_query_storage-v1beta1.ts.baseline b/baselines/bigquery-storage/test/gapic-big_query_storage-v1beta1.ts.baseline index f21cc6581..7d9f3e076 100644 --- a/baselines/bigquery-storage/test/gapic-big_query_storage-v1beta1.ts.baseline +++ b/baselines/bigquery-storage/test/gapic-big_query_storage-v1beta1.ts.baseline @@ -97,12 +97,30 @@ describe('v1beta1.BigQueryStorageClient', () => { }); assert(client); }); + it('has initialize method and supports deferred initialization', async () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.bigQueryStorageStub, undefined); + await client.initialize(); + assert(client.bigQueryStorageStub); + }); + it('has close method', () => { + const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.close(); + }); describe('createReadSession', () => { it('invokes createReadSession without error', done => { const client = new bigquerystorageModule.v1beta1.BigQueryStorageClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest = {}; request.tableReference = {}; @@ -129,6 +147,8 @@ describe('v1beta1.BigQueryStorageClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.bigquery.storage.v1beta1.ICreateReadSessionRequest = {}; request.tableReference = {}; @@ -157,6 +177,8 @@ describe('v1beta1.BigQueryStorageClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest = {}; request.session = {}; @@ -181,6 +203,8 @@ describe('v1beta1.BigQueryStorageClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.bigquery.storage.v1beta1.IBatchCreateReadSessionStreamsRequest = {}; request.session = {}; @@ -207,6 +231,8 @@ describe('v1beta1.BigQueryStorageClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest = {}; request.stream = {}; @@ -231,6 +257,8 @@ describe('v1beta1.BigQueryStorageClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.bigquery.storage.v1beta1.IFinalizeStreamRequest = {}; request.stream = {}; @@ -257,6 +285,8 @@ describe('v1beta1.BigQueryStorageClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest = {}; request.originalStream = {}; @@ -281,6 +311,8 @@ describe('v1beta1.BigQueryStorageClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.bigquery.storage.v1beta1.ISplitReadStreamRequest = {}; request.originalStream = {}; @@ -307,6 +339,8 @@ describe('v1beta1.BigQueryStorageClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.bigquery.storage.v1beta1.IReadRowsRequest = {}; request.readPosition = {}; @@ -331,6 +365,8 @@ describe('v1beta1.BigQueryStorageClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.bigquery.storage.v1beta1.IReadRowsRequest = {}; request.readPosition = {}; diff --git a/baselines/dlp/src/v2/dlp_service_client.ts.baseline b/baselines/dlp/src/v2/dlp_service_client.ts.baseline index 4590b416b..9f8d0bbd7 100644 --- a/baselines/dlp/src/v2/dlp_service_client.ts.baseline +++ b/baselines/dlp/src/v2/dlp_service_client.ts.baseline @@ -44,8 +44,13 @@ export class DlpServiceClient { private _innerApiCalls: {[name: string]: Function}; private _pathTemplates: {[name: string]: gax.PathTemplate}; private _terminated = false; + private _opts: ClientOptions; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; auth: gax.GoogleAuth; - dlpServiceStub: Promise<{[name: string]: Function}>; + dlpServiceStub?: Promise<{[name: string]: Function}>; /** * Construct an instance of DlpServiceClient. @@ -98,28 +103,31 @@ export class DlpServiceClient { // If we are in browser, we are already using fallback because of the // "browser" field in package.json. // But if we were explicitly requested to use fallback, let's do it now. - const gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; + this._gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; // Create a `gaxGrpc` object, with any grpc-specific options // sent to the client. opts.scopes = (this.constructor as typeof DlpServiceClient).scopes; - const gaxGrpc = new gaxModule.GrpcClient(opts); + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (gaxGrpc.auth as gax.GoogleAuth); + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); // Determine the client header string. const clientHeader = [ - `gax/${gaxModule.version}`, + `gax/${this._gaxModule.version}`, `gapic/${version}`, ]; if (typeof process !== 'undefined' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { - clientHeader.push(`gl-web/${gaxModule.version}`); + clientHeader.push(`gl-web/${this._gaxModule.version}`); } if (!opts.fallback) { - clientHeader.push(`grpc/${gaxGrpc.grpcVersion}`); + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { clientHeader.push(`${opts.libName}/${opts.libVersion}`); @@ -129,7 +137,7 @@ export class DlpServiceClient { // For browsers, pass the JSON content. const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); - const protos = gaxGrpc.loadProto( + this._protos = this._gaxGrpc.loadProto( opts.fallback ? require("../../protos/protos.json") : nodejsProtoPath @@ -139,34 +147,34 @@ export class DlpServiceClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this._pathTemplates = { - dlpJobPathTemplate: new gaxModule.PathTemplate( + dlpJobPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/dlpJobs/{dlp_job}' ), - jobTriggerPathTemplate: new gaxModule.PathTemplate( + jobTriggerPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/jobTriggers/{job_trigger}' ), - organizationPathTemplate: new gaxModule.PathTemplate( + organizationPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}' ), - organizationDeidentifyTemplatePathTemplate: new gaxModule.PathTemplate( + organizationDeidentifyTemplatePathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/deidentifyTemplates/{deidentify_template}' ), - organizationInspectTemplatePathTemplate: new gaxModule.PathTemplate( + organizationInspectTemplatePathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/inspectTemplates/{inspect_template}' ), - organizationStoredInfoTypePathTemplate: new gaxModule.PathTemplate( + organizationStoredInfoTypePathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/storedInfoTypes/{stored_info_type}' ), - projectPathTemplate: new gaxModule.PathTemplate( + projectPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}' ), - projectDeidentifyTemplatePathTemplate: new gaxModule.PathTemplate( + projectDeidentifyTemplatePathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/deidentifyTemplates/{deidentify_template}' ), - projectInspectTemplatePathTemplate: new gaxModule.PathTemplate( + projectInspectTemplatePathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/inspectTemplates/{inspect_template}' ), - projectStoredInfoTypePathTemplate: new gaxModule.PathTemplate( + projectStoredInfoTypePathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/storedInfoTypes/{stored_info_type}' ), }; @@ -176,19 +184,19 @@ export class DlpServiceClient { // pages). Denote the keys used for pagination and results. this._descriptors.page = { listInspectTemplates: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'inspectTemplates'), + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'inspectTemplates'), listDeidentifyTemplates: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'deidentifyTemplates'), + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'deidentifyTemplates'), listJobTriggers: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'jobTriggers'), + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'jobTriggers'), listDlpJobs: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'jobs'), + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'jobs'), listStoredInfoTypes: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'storedInfoTypes') + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'storedInfoTypes') }; // Put together the default options sent with requests. - const defaults = gaxGrpc.constructSettings( + this._defaults = this._gaxGrpc.constructSettings( 'google.privacy.dlp.v2.DlpService', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); @@ -196,15 +204,33 @@ export class DlpServiceClient { // of calling the API is handled in `google-gax`, with this code // merely providing the destination and request information. this._innerApiCalls = {}; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.dlpServiceStub) { + return this.dlpServiceStub; + } // Put together the "service stub" for // google.privacy.dlp.v2.DlpService. - this.dlpServiceStub = gaxGrpc.createStub( - opts.fallback ? - (protos as protobuf.Root).lookupService('google.privacy.dlp.v2.DlpService') : + this.dlpServiceStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.privacy.dlp.v2.DlpService') : // tslint:disable-next-line no-any - (protos as any).google.privacy.dlp.v2.DlpService, - opts) as Promise<{[method: string]: Function}>; + (this._protos as any).google.privacy.dlp.v2.DlpService, + this._opts) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -223,9 +249,9 @@ export class DlpServiceClient { throw err; }); - const apiCall = gaxModule.createApiCall( + const apiCall = this._gaxModule.createApiCall( innerCallPromise, - defaults[methodName], + this._defaults[methodName], this._descriptors.page[methodName] || this._descriptors.stream[methodName] || this._descriptors.longrunning[methodName] @@ -239,6 +265,8 @@ export class DlpServiceClient { return apiCall(argument, callOptions, callback); }; } + + return this.dlpServiceStub; } /** @@ -371,6 +399,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.inspectContent(request, options, callback); } redactImage( @@ -449,6 +478,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.redactImage(request, options, callback); } deidentifyContent( @@ -540,6 +570,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.deidentifyContent(request, options, callback); } reidentifyContent( @@ -633,6 +664,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.reidentifyContent(request, options, callback); } listInfoTypes( @@ -695,6 +727,7 @@ export class DlpServiceClient { options = optionsOrCallback as gax.CallOptions; } options = options || {}; + this.initialize(); return this._innerApiCalls.listInfoTypes(request, options, callback); } createInspectTemplate( @@ -767,6 +800,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.createInspectTemplate(request, options, callback); } updateInspectTemplate( @@ -833,6 +867,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.updateInspectTemplate(request, options, callback); } getInspectTemplate( @@ -895,6 +930,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.getInspectTemplate(request, options, callback); } deleteInspectTemplate( @@ -957,6 +993,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.deleteInspectTemplate(request, options, callback); } createDeidentifyTemplate( @@ -1030,6 +1067,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.createDeidentifyTemplate(request, options, callback); } updateDeidentifyTemplate( @@ -1097,6 +1135,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.updateDeidentifyTemplate(request, options, callback); } getDeidentifyTemplate( @@ -1160,6 +1199,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.getDeidentifyTemplate(request, options, callback); } deleteDeidentifyTemplate( @@ -1223,6 +1263,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.deleteDeidentifyTemplate(request, options, callback); } createJobTrigger( @@ -1294,6 +1335,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.createJobTrigger(request, options, callback); } updateJobTrigger( @@ -1359,6 +1401,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.updateJobTrigger(request, options, callback); } getJobTrigger( @@ -1420,6 +1463,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.getJobTrigger(request, options, callback); } deleteJobTrigger( @@ -1481,6 +1525,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.deleteJobTrigger(request, options, callback); } activateJobTrigger( @@ -1542,6 +1587,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.activateJobTrigger(request, options, callback); } createDlpJob( @@ -1619,6 +1665,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.createDlpJob(request, options, callback); } getDlpJob( @@ -1680,6 +1727,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.getDlpJob(request, options, callback); } deleteDlpJob( @@ -1743,6 +1791,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.deleteDlpJob(request, options, callback); } cancelDlpJob( @@ -1806,6 +1855,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.cancelDlpJob(request, options, callback); } createStoredInfoType( @@ -1878,6 +1928,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.createStoredInfoType(request, options, callback); } updateStoredInfoType( @@ -1948,6 +1999,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.updateStoredInfoType(request, options, callback); } getStoredInfoType( @@ -2011,6 +2063,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.getStoredInfoType(request, options, callback); } deleteStoredInfoType( @@ -2074,6 +2127,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.deleteStoredInfoType(request, options, callback); } @@ -2174,6 +2228,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.listInspectTemplates(request, options, callback); } @@ -2237,6 +2292,7 @@ export class DlpServiceClient { 'parent': request.parent || '', }); const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listInspectTemplates.createStream( this._innerApiCalls.listInspectTemplates as gax.GaxCall, request, @@ -2341,6 +2397,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.listDeidentifyTemplates(request, options, callback); } @@ -2404,6 +2461,7 @@ export class DlpServiceClient { 'parent': request.parent || '', }); const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listDeidentifyTemplates.createStream( this._innerApiCalls.listDeidentifyTemplates as gax.GaxCall, request, @@ -2533,6 +2591,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.listJobTriggers(request, options, callback); } @@ -2622,6 +2681,7 @@ export class DlpServiceClient { 'parent': request.parent || '', }); const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listJobTriggers.createStream( this._innerApiCalls.listJobTriggers as gax.GaxCall, request, @@ -2754,6 +2814,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.listDlpJobs(request, options, callback); } @@ -2845,6 +2906,7 @@ export class DlpServiceClient { 'parent': request.parent || '', }); const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listDlpJobs.createStream( this._innerApiCalls.listDlpJobs as gax.GaxCall, request, @@ -2950,6 +3012,7 @@ export class DlpServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.listStoredInfoTypes(request, options, callback); } @@ -3014,6 +3077,7 @@ export class DlpServiceClient { 'parent': request.parent || '', }); const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listStoredInfoTypes.createStream( this._innerApiCalls.listStoredInfoTypes as gax.GaxCall, request, @@ -3364,8 +3428,9 @@ export class DlpServiceClient { * The client will no longer be usable and all future behavior is undefined. */ close(): Promise { + this.initialize(); if (!this._terminated) { - return this.dlpServiceStub.then(stub => { + return this.dlpServiceStub!.then(stub => { this._terminated = true; stub.close(); }); diff --git a/baselines/dlp/test/gapic-dlp_service-v2.ts.baseline b/baselines/dlp/test/gapic-dlp_service-v2.ts.baseline index 3d9f65d0e..54c9ad3a0 100644 --- a/baselines/dlp/test/gapic-dlp_service-v2.ts.baseline +++ b/baselines/dlp/test/gapic-dlp_service-v2.ts.baseline @@ -78,12 +78,30 @@ describe('v2.DlpServiceClient', () => { }); assert(client); }); + it('has initialize method and supports deferred initialization', async () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.dlpServiceStub, undefined); + await client.initialize(); + assert(client.dlpServiceStub); + }); + it('has close method', () => { + const client = new dlpserviceModule.v2.DlpServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.close(); + }); describe('inspectContent', () => { it('invokes inspectContent without error', done => { const client = new dlpserviceModule.v2.DlpServiceClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IInspectContentRequest = {}; request.parent = ''; @@ -107,6 +125,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IInspectContentRequest = {}; request.parent = ''; @@ -132,6 +152,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IRedactImageRequest = {}; request.parent = ''; @@ -155,6 +177,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IRedactImageRequest = {}; request.parent = ''; @@ -180,6 +204,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IDeidentifyContentRequest = {}; request.parent = ''; @@ -203,6 +229,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IDeidentifyContentRequest = {}; request.parent = ''; @@ -228,6 +256,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IReidentifyContentRequest = {}; request.parent = ''; @@ -251,6 +281,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IReidentifyContentRequest = {}; request.parent = ''; @@ -276,6 +308,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IListInfoTypesRequest = {}; // Mock response @@ -298,6 +332,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IListInfoTypesRequest = {}; // Mock response @@ -322,6 +358,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.ICreateInspectTemplateRequest = {}; request.parent = ''; @@ -345,6 +383,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.ICreateInspectTemplateRequest = {}; request.parent = ''; @@ -370,6 +410,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IUpdateInspectTemplateRequest = {}; request.name = ''; @@ -393,6 +435,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IUpdateInspectTemplateRequest = {}; request.name = ''; @@ -418,6 +462,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IGetInspectTemplateRequest = {}; request.name = ''; @@ -441,6 +487,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IGetInspectTemplateRequest = {}; request.name = ''; @@ -466,6 +514,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IDeleteInspectTemplateRequest = {}; request.name = ''; @@ -489,6 +539,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IDeleteInspectTemplateRequest = {}; request.name = ''; @@ -514,6 +566,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest = {}; request.parent = ''; @@ -537,6 +591,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.ICreateDeidentifyTemplateRequest = {}; request.parent = ''; @@ -562,6 +618,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest = {}; request.name = ''; @@ -585,6 +643,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IUpdateDeidentifyTemplateRequest = {}; request.name = ''; @@ -610,6 +670,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest = {}; request.name = ''; @@ -633,6 +695,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IGetDeidentifyTemplateRequest = {}; request.name = ''; @@ -658,6 +722,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest = {}; request.name = ''; @@ -681,6 +747,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IDeleteDeidentifyTemplateRequest = {}; request.name = ''; @@ -706,6 +774,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.ICreateJobTriggerRequest = {}; request.parent = ''; @@ -729,6 +799,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.ICreateJobTriggerRequest = {}; request.parent = ''; @@ -754,6 +826,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IUpdateJobTriggerRequest = {}; request.name = ''; @@ -777,6 +851,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IUpdateJobTriggerRequest = {}; request.name = ''; @@ -802,6 +878,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IGetJobTriggerRequest = {}; request.name = ''; @@ -825,6 +903,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IGetJobTriggerRequest = {}; request.name = ''; @@ -850,6 +930,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IDeleteJobTriggerRequest = {}; request.name = ''; @@ -873,6 +955,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IDeleteJobTriggerRequest = {}; request.name = ''; @@ -898,6 +982,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IActivateJobTriggerRequest = {}; request.name = ''; @@ -921,6 +1007,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IActivateJobTriggerRequest = {}; request.name = ''; @@ -946,6 +1034,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.ICreateDlpJobRequest = {}; request.parent = ''; @@ -969,6 +1059,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.ICreateDlpJobRequest = {}; request.parent = ''; @@ -994,6 +1086,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IGetDlpJobRequest = {}; request.name = ''; @@ -1017,6 +1111,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IGetDlpJobRequest = {}; request.name = ''; @@ -1042,6 +1138,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IDeleteDlpJobRequest = {}; request.name = ''; @@ -1065,6 +1163,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IDeleteDlpJobRequest = {}; request.name = ''; @@ -1090,6 +1190,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.ICancelDlpJobRequest = {}; request.name = ''; @@ -1113,6 +1215,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.ICancelDlpJobRequest = {}; request.name = ''; @@ -1138,6 +1242,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest = {}; request.parent = ''; @@ -1161,6 +1267,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.ICreateStoredInfoTypeRequest = {}; request.parent = ''; @@ -1186,6 +1294,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest = {}; request.name = ''; @@ -1209,6 +1319,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IUpdateStoredInfoTypeRequest = {}; request.name = ''; @@ -1234,6 +1346,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IGetStoredInfoTypeRequest = {}; request.name = ''; @@ -1257,6 +1371,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IGetStoredInfoTypeRequest = {}; request.name = ''; @@ -1282,6 +1398,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest = {}; request.name = ''; @@ -1305,6 +1423,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IDeleteStoredInfoTypeRequest = {}; request.name = ''; @@ -1330,6 +1450,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IListInspectTemplatesRequest = {}; request.parent = ''; @@ -1353,6 +1475,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IListInspectTemplatesRequest = {}; request.parent = ''; @@ -1378,6 +1502,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest = {}; request.parent = ''; @@ -1401,6 +1527,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IListDeidentifyTemplatesRequest = {}; request.parent = ''; @@ -1426,6 +1554,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IListJobTriggersRequest = {}; request.parent = ''; @@ -1449,6 +1579,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IListJobTriggersRequest = {}; request.parent = ''; @@ -1474,6 +1606,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IListDlpJobsRequest = {}; request.parent = ''; @@ -1497,6 +1631,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IListDlpJobsRequest = {}; request.parent = ''; @@ -1522,6 +1658,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IListStoredInfoTypesRequest = {}; request.parent = ''; @@ -1545,6 +1683,8 @@ describe('v2.DlpServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.privacy.dlp.v2.IListStoredInfoTypesRequest = {}; request.parent = ''; diff --git a/baselines/kms/src/v1/key_management_service_client.ts.baseline b/baselines/kms/src/v1/key_management_service_client.ts.baseline index 1a92dc14c..43533120f 100644 --- a/baselines/kms/src/v1/key_management_service_client.ts.baseline +++ b/baselines/kms/src/v1/key_management_service_client.ts.baseline @@ -45,8 +45,13 @@ export class KeyManagementServiceClient { private _descriptors: Descriptors = {page: {}, stream: {}, longrunning: {}}; private _innerApiCalls: {[name: string]: Function}; private _terminated = false; + private _opts: ClientOptions; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; auth: gax.GoogleAuth; - keyManagementServiceStub: Promise<{[name: string]: Function}>; + keyManagementServiceStub?: Promise<{[name: string]: Function}>; /** * Construct an instance of KeyManagementServiceClient. @@ -99,28 +104,31 @@ export class KeyManagementServiceClient { // If we are in browser, we are already using fallback because of the // "browser" field in package.json. // But if we were explicitly requested to use fallback, let's do it now. - const gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; + this._gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; // Create a `gaxGrpc` object, with any grpc-specific options // sent to the client. opts.scopes = (this.constructor as typeof KeyManagementServiceClient).scopes; - const gaxGrpc = new gaxModule.GrpcClient(opts); + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (gaxGrpc.auth as gax.GoogleAuth); + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); // Determine the client header string. const clientHeader = [ - `gax/${gaxModule.version}`, + `gax/${this._gaxModule.version}`, `gapic/${version}`, ]; if (typeof process !== 'undefined' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { - clientHeader.push(`gl-web/${gaxModule.version}`); + clientHeader.push(`gl-web/${this._gaxModule.version}`); } if (!opts.fallback) { - clientHeader.push(`grpc/${gaxGrpc.grpcVersion}`); + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { clientHeader.push(`${opts.libName}/${opts.libVersion}`); @@ -130,7 +138,7 @@ export class KeyManagementServiceClient { // For browsers, pass the JSON content. const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); - const protos = gaxGrpc.loadProto( + this._protos = this._gaxGrpc.loadProto( opts.fallback ? require("../../protos/protos.json") : nodejsProtoPath @@ -141,17 +149,17 @@ export class KeyManagementServiceClient { // pages). Denote the keys used for pagination and results. this._descriptors.page = { listKeyRings: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'keyRings'), + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'keyRings'), listCryptoKeys: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'cryptoKeys'), + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'cryptoKeys'), listCryptoKeyVersions: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'cryptoKeyVersions'), + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'cryptoKeyVersions'), listImportJobs: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'importJobs') + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'importJobs') }; // Put together the default options sent with requests. - const defaults = gaxGrpc.constructSettings( + this._defaults = this._gaxGrpc.constructSettings( 'google.cloud.kms.v1.KeyManagementService', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); @@ -159,15 +167,33 @@ export class KeyManagementServiceClient { // of calling the API is handled in `google-gax`, with this code // merely providing the destination and request information. this._innerApiCalls = {}; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.keyManagementServiceStub) { + return this.keyManagementServiceStub; + } // Put together the "service stub" for // google.cloud.kms.v1.KeyManagementService. - this.keyManagementServiceStub = gaxGrpc.createStub( - opts.fallback ? - (protos as protobuf.Root).lookupService('google.cloud.kms.v1.KeyManagementService') : + this.keyManagementServiceStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.cloud.kms.v1.KeyManagementService') : // tslint:disable-next-line no-any - (protos as any).google.cloud.kms.v1.KeyManagementService, - opts) as Promise<{[method: string]: Function}>; + (this._protos as any).google.cloud.kms.v1.KeyManagementService, + this._opts) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -186,9 +212,9 @@ export class KeyManagementServiceClient { throw err; }); - const apiCall = gaxModule.createApiCall( + const apiCall = this._gaxModule.createApiCall( innerCallPromise, - defaults[methodName], + this._defaults[methodName], this._descriptors.page[methodName] || this._descriptors.stream[methodName] || this._descriptors.longrunning[methodName] @@ -202,6 +228,8 @@ export class KeyManagementServiceClient { return apiCall(argument, callOptions, callback); }; } + + return this.keyManagementServiceStub; } /** @@ -313,6 +341,7 @@ export class KeyManagementServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.getKeyRing(request, options, callback); } getCryptoKey( @@ -373,6 +402,7 @@ export class KeyManagementServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.getCryptoKey(request, options, callback); } getCryptoKeyVersion( @@ -432,6 +462,7 @@ export class KeyManagementServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.getCryptoKeyVersion(request, options, callback); } getPublicKey( @@ -495,6 +526,7 @@ export class KeyManagementServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.getPublicKey(request, options, callback); } getImportJob( @@ -554,6 +586,7 @@ export class KeyManagementServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.getImportJob(request, options, callback); } createKeyRing( @@ -619,6 +652,7 @@ export class KeyManagementServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.createKeyRing(request, options, callback); } createCryptoKey( @@ -694,6 +728,7 @@ export class KeyManagementServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.createCryptoKey(request, options, callback); } createCryptoKeyVersion( @@ -760,6 +795,7 @@ export class KeyManagementServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.createCryptoKeyVersion(request, options, callback); } importCryptoKeyVersion( @@ -851,6 +887,7 @@ export class KeyManagementServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.importCryptoKeyVersion(request, options, callback); } createImportJob( @@ -918,6 +955,7 @@ export class KeyManagementServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.createImportJob(request, options, callback); } updateCryptoKey( @@ -979,6 +1017,7 @@ export class KeyManagementServiceClient { ] = gax.routingHeader.fromParams({ 'crypto_key.name': request.cryptoKey!.name || '', }); + this.initialize(); return this._innerApiCalls.updateCryptoKey(request, options, callback); } updateCryptoKeyVersion( @@ -1046,6 +1085,7 @@ export class KeyManagementServiceClient { ] = gax.routingHeader.fromParams({ 'crypto_key_version.name': request.cryptoKeyVersion!.name || '', }); + this.initialize(); return this._innerApiCalls.updateCryptoKeyVersion(request, options, callback); } encrypt( @@ -1130,6 +1170,7 @@ export class KeyManagementServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.encrypt(request, options, callback); } decrypt( @@ -1197,6 +1238,7 @@ export class KeyManagementServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.decrypt(request, options, callback); } asymmetricSign( @@ -1262,6 +1304,7 @@ export class KeyManagementServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.asymmetricSign(request, options, callback); } asymmetricDecrypt( @@ -1327,6 +1370,7 @@ export class KeyManagementServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.asymmetricDecrypt(request, options, callback); } updateCryptoKeyPrimaryVersion( @@ -1390,6 +1434,7 @@ export class KeyManagementServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.updateCryptoKeyPrimaryVersion(request, options, callback); } destroyCryptoKeyVersion( @@ -1460,6 +1505,7 @@ export class KeyManagementServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.destroyCryptoKeyVersion(request, options, callback); } restoreCryptoKeyVersion( @@ -1525,6 +1571,7 @@ export class KeyManagementServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.restoreCryptoKeyVersion(request, options, callback); } @@ -1614,6 +1661,7 @@ export class KeyManagementServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.listKeyRings(request, options, callback); } @@ -1667,6 +1715,7 @@ export class KeyManagementServiceClient { 'parent': request.parent || '', }); const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listKeyRings.createStream( this._innerApiCalls.listKeyRings as gax.GaxCall, request, @@ -1761,6 +1810,7 @@ export class KeyManagementServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.listCryptoKeys(request, options, callback); } @@ -1816,6 +1866,7 @@ export class KeyManagementServiceClient { 'parent': request.parent || '', }); const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listCryptoKeys.createStream( this._innerApiCalls.listCryptoKeys as gax.GaxCall, request, @@ -1911,6 +1962,7 @@ export class KeyManagementServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.listCryptoKeyVersions(request, options, callback); } @@ -1967,6 +2019,7 @@ export class KeyManagementServiceClient { 'parent': request.parent || '', }); const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listCryptoKeyVersions.createStream( this._innerApiCalls.listCryptoKeyVersions as gax.GaxCall, request, @@ -2059,6 +2112,7 @@ export class KeyManagementServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.listImportJobs(request, options, callback); } @@ -2112,6 +2166,7 @@ export class KeyManagementServiceClient { 'parent': request.parent || '', }); const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listImportJobs.createStream( this._innerApiCalls.listImportJobs as gax.GaxCall, request, @@ -2125,8 +2180,9 @@ export class KeyManagementServiceClient { * The client will no longer be usable and all future behavior is undefined. */ close(): Promise { + this.initialize(); if (!this._terminated) { - return this.keyManagementServiceStub.then(stub => { + return this.keyManagementServiceStub!.then(stub => { this._terminated = true; stub.close(); }); diff --git a/baselines/kms/test/gapic-key_management_service-v1.ts.baseline b/baselines/kms/test/gapic-key_management_service-v1.ts.baseline index b15bde0a6..ad4b25ba4 100644 --- a/baselines/kms/test/gapic-key_management_service-v1.ts.baseline +++ b/baselines/kms/test/gapic-key_management_service-v1.ts.baseline @@ -78,12 +78,30 @@ describe('v1.KeyManagementServiceClient', () => { }); assert(client); }); + it('has initialize method and supports deferred initialization', async () => { + const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.keyManagementServiceStub, undefined); + await client.initialize(); + assert(client.keyManagementServiceStub); + }); + it('has close method', () => { + const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.close(); + }); describe('getKeyRing', () => { it('invokes getKeyRing without error', done => { const client = new keymanagementserviceModule.v1.KeyManagementServiceClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IGetKeyRingRequest = {}; request.name = ''; @@ -107,6 +125,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IGetKeyRingRequest = {}; request.name = ''; @@ -132,6 +152,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IGetCryptoKeyRequest = {}; request.name = ''; @@ -155,6 +177,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IGetCryptoKeyRequest = {}; request.name = ''; @@ -180,6 +204,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IGetCryptoKeyVersionRequest = {}; request.name = ''; @@ -203,6 +229,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IGetCryptoKeyVersionRequest = {}; request.name = ''; @@ -228,6 +256,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IGetPublicKeyRequest = {}; request.name = ''; @@ -251,6 +281,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IGetPublicKeyRequest = {}; request.name = ''; @@ -276,6 +308,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IGetImportJobRequest = {}; request.name = ''; @@ -299,6 +333,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IGetImportJobRequest = {}; request.name = ''; @@ -324,6 +360,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.ICreateKeyRingRequest = {}; request.parent = ''; @@ -347,6 +385,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.ICreateKeyRingRequest = {}; request.parent = ''; @@ -372,6 +412,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.ICreateCryptoKeyRequest = {}; request.parent = ''; @@ -395,6 +437,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.ICreateCryptoKeyRequest = {}; request.parent = ''; @@ -420,6 +464,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest = {}; request.parent = ''; @@ -443,6 +489,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.ICreateCryptoKeyVersionRequest = {}; request.parent = ''; @@ -468,6 +516,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IImportCryptoKeyVersionRequest = {}; request.parent = ''; @@ -491,6 +541,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IImportCryptoKeyVersionRequest = {}; request.parent = ''; @@ -516,6 +568,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.ICreateImportJobRequest = {}; request.parent = ''; @@ -539,6 +593,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.ICreateImportJobRequest = {}; request.parent = ''; @@ -564,6 +620,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IUpdateCryptoKeyRequest = {}; request.cryptoKey = {}; @@ -588,6 +646,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IUpdateCryptoKeyRequest = {}; request.cryptoKey = {}; @@ -614,6 +674,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest = {}; request.cryptoKeyVersion = {}; @@ -638,6 +700,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IUpdateCryptoKeyVersionRequest = {}; request.cryptoKeyVersion = {}; @@ -664,6 +728,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IEncryptRequest = {}; request.name = ''; @@ -687,6 +753,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IEncryptRequest = {}; request.name = ''; @@ -712,6 +780,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IDecryptRequest = {}; request.name = ''; @@ -735,6 +805,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IDecryptRequest = {}; request.name = ''; @@ -760,6 +832,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IAsymmetricSignRequest = {}; request.name = ''; @@ -783,6 +857,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IAsymmetricSignRequest = {}; request.name = ''; @@ -808,6 +884,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IAsymmetricDecryptRequest = {}; request.name = ''; @@ -831,6 +909,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IAsymmetricDecryptRequest = {}; request.name = ''; @@ -856,6 +936,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest = {}; request.name = ''; @@ -879,6 +961,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IUpdateCryptoKeyPrimaryVersionRequest = {}; request.name = ''; @@ -904,6 +988,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest = {}; request.name = ''; @@ -927,6 +1013,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IDestroyCryptoKeyVersionRequest = {}; request.name = ''; @@ -952,6 +1040,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest = {}; request.name = ''; @@ -975,6 +1065,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IRestoreCryptoKeyVersionRequest = {}; request.name = ''; @@ -1000,6 +1092,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IListKeyRingsRequest = {}; request.parent = ''; @@ -1023,6 +1117,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IListKeyRingsRequest = {}; request.parent = ''; @@ -1048,6 +1144,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IListCryptoKeysRequest = {}; request.parent = ''; @@ -1071,6 +1169,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IListCryptoKeysRequest = {}; request.parent = ''; @@ -1096,6 +1196,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IListCryptoKeyVersionsRequest = {}; request.parent = ''; @@ -1119,6 +1221,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IListCryptoKeyVersionsRequest = {}; request.parent = ''; @@ -1144,6 +1248,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IListImportJobsRequest = {}; request.parent = ''; @@ -1167,6 +1273,8 @@ describe('v1.KeyManagementServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.kms.v1.IListImportJobsRequest = {}; request.parent = ''; diff --git a/baselines/monitoring/src/v3/alert_policy_service_client.ts.baseline b/baselines/monitoring/src/v3/alert_policy_service_client.ts.baseline index 3a220fd38..c69322823 100644 --- a/baselines/monitoring/src/v3/alert_policy_service_client.ts.baseline +++ b/baselines/monitoring/src/v3/alert_policy_service_client.ts.baseline @@ -44,8 +44,13 @@ export class AlertPolicyServiceClient { private _innerApiCalls: {[name: string]: Function}; private _pathTemplates: {[name: string]: gax.PathTemplate}; private _terminated = false; + private _opts: ClientOptions; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; auth: gax.GoogleAuth; - alertPolicyServiceStub: Promise<{[name: string]: Function}>; + alertPolicyServiceStub?: Promise<{[name: string]: Function}>; /** * Construct an instance of AlertPolicyServiceClient. @@ -98,28 +103,31 @@ export class AlertPolicyServiceClient { // If we are in browser, we are already using fallback because of the // "browser" field in package.json. // But if we were explicitly requested to use fallback, let's do it now. - const gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; + this._gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; // Create a `gaxGrpc` object, with any grpc-specific options // sent to the client. opts.scopes = (this.constructor as typeof AlertPolicyServiceClient).scopes; - const gaxGrpc = new gaxModule.GrpcClient(opts); + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (gaxGrpc.auth as gax.GoogleAuth); + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); // Determine the client header string. const clientHeader = [ - `gax/${gaxModule.version}`, + `gax/${this._gaxModule.version}`, `gapic/${version}`, ]; if (typeof process !== 'undefined' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { - clientHeader.push(`gl-web/${gaxModule.version}`); + clientHeader.push(`gl-web/${this._gaxModule.version}`); } if (!opts.fallback) { - clientHeader.push(`grpc/${gaxGrpc.grpcVersion}`); + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { clientHeader.push(`${opts.libName}/${opts.libVersion}`); @@ -129,7 +137,7 @@ export class AlertPolicyServiceClient { // For browsers, pass the JSON content. const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); - const protos = gaxGrpc.loadProto( + this._protos = this._gaxGrpc.loadProto( opts.fallback ? require("../../protos/protos.json") : nodejsProtoPath @@ -139,76 +147,76 @@ export class AlertPolicyServiceClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this._pathTemplates = { - folderAlertPolicyPathTemplate: new gaxModule.PathTemplate( + folderAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/alertPolicies/{alert_policy}' ), - folderAlertPolicyConditionPathTemplate: new gaxModule.PathTemplate( + folderAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}' ), - folderChannelDescriptorPathTemplate: new gaxModule.PathTemplate( + folderChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}' ), - folderGroupPathTemplate: new gaxModule.PathTemplate( + folderGroupPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/groups/{group}' ), - folderNotificationChannelPathTemplate: new gaxModule.PathTemplate( + folderNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/notificationChannels/{notification_channel}' ), - folderServicePathTemplate: new gaxModule.PathTemplate( + folderServicePathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/services/{service}' ), - folderServiceServiceLevelObjectivePathTemplate: new gaxModule.PathTemplate( + folderServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}' ), - folderUptimeCheckConfigPathTemplate: new gaxModule.PathTemplate( + folderUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}' ), - organizationAlertPolicyPathTemplate: new gaxModule.PathTemplate( + organizationAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/alertPolicies/{alert_policy}' ), - organizationAlertPolicyConditionPathTemplate: new gaxModule.PathTemplate( + organizationAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}' ), - organizationChannelDescriptorPathTemplate: new gaxModule.PathTemplate( + organizationChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}' ), - organizationGroupPathTemplate: new gaxModule.PathTemplate( + organizationGroupPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/groups/{group}' ), - organizationNotificationChannelPathTemplate: new gaxModule.PathTemplate( + organizationNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/notificationChannels/{notification_channel}' ), - organizationServicePathTemplate: new gaxModule.PathTemplate( + organizationServicePathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/services/{service}' ), - organizationServiceServiceLevelObjectivePathTemplate: new gaxModule.PathTemplate( + organizationServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}' ), - organizationUptimeCheckConfigPathTemplate: new gaxModule.PathTemplate( + organizationUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}' ), - projectAlertPolicyPathTemplate: new gaxModule.PathTemplate( + projectAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/alertPolicies/{alert_policy}' ), - projectAlertPolicyConditionPathTemplate: new gaxModule.PathTemplate( + projectAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}' ), - projectChannelDescriptorPathTemplate: new gaxModule.PathTemplate( + projectChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}' ), - projectGroupPathTemplate: new gaxModule.PathTemplate( + projectGroupPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/groups/{group}' ), - projectNotificationChannelPathTemplate: new gaxModule.PathTemplate( + projectNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/notificationChannels/{notification_channel}' ), - projectServicePathTemplate: new gaxModule.PathTemplate( + projectServicePathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/services/{service}' ), - projectServiceServiceLevelObjectivePathTemplate: new gaxModule.PathTemplate( + projectServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}' ), - projectUptimeCheckConfigPathTemplate: new gaxModule.PathTemplate( + projectUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}' ), }; @@ -218,11 +226,11 @@ export class AlertPolicyServiceClient { // pages). Denote the keys used for pagination and results. this._descriptors.page = { listAlertPolicies: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'alertPolicies') + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'alertPolicies') }; // Put together the default options sent with requests. - const defaults = gaxGrpc.constructSettings( + this._defaults = this._gaxGrpc.constructSettings( 'google.monitoring.v3.AlertPolicyService', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); @@ -230,15 +238,33 @@ export class AlertPolicyServiceClient { // of calling the API is handled in `google-gax`, with this code // merely providing the destination and request information. this._innerApiCalls = {}; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.alertPolicyServiceStub) { + return this.alertPolicyServiceStub; + } // Put together the "service stub" for // google.monitoring.v3.AlertPolicyService. - this.alertPolicyServiceStub = gaxGrpc.createStub( - opts.fallback ? - (protos as protobuf.Root).lookupService('google.monitoring.v3.AlertPolicyService') : + this.alertPolicyServiceStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.monitoring.v3.AlertPolicyService') : // tslint:disable-next-line no-any - (protos as any).google.monitoring.v3.AlertPolicyService, - opts) as Promise<{[method: string]: Function}>; + (this._protos as any).google.monitoring.v3.AlertPolicyService, + this._opts) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -257,9 +283,9 @@ export class AlertPolicyServiceClient { throw err; }); - const apiCall = gaxModule.createApiCall( + const apiCall = this._gaxModule.createApiCall( innerCallPromise, - defaults[methodName], + this._defaults[methodName], this._descriptors.page[methodName] || this._descriptors.stream[methodName] || this._descriptors.longrunning[methodName] @@ -273,6 +299,8 @@ export class AlertPolicyServiceClient { return apiCall(argument, callOptions, callback); }; } + + return this.alertPolicyServiceStub; } /** @@ -387,6 +415,7 @@ export class AlertPolicyServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.getAlertPolicy(request, options, callback); } createAlertPolicy( @@ -457,6 +486,7 @@ export class AlertPolicyServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.createAlertPolicy(request, options, callback); } deleteAlertPolicy( @@ -520,6 +550,7 @@ export class AlertPolicyServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.deleteAlertPolicy(request, options, callback); } updateAlertPolicy( @@ -607,6 +638,7 @@ export class AlertPolicyServiceClient { ] = gax.routingHeader.fromParams({ 'alert_policy.name': request.alertPolicy!.name || '', }); + this.initialize(); return this._innerApiCalls.updateAlertPolicy(request, options, callback); } @@ -709,6 +741,7 @@ export class AlertPolicyServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.listAlertPolicies(request, options, callback); } @@ -775,6 +808,7 @@ export class AlertPolicyServiceClient { 'name': request.name || '', }); const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listAlertPolicies.createStream( this._innerApiCalls.listAlertPolicies as gax.GaxCall, request, @@ -1733,8 +1767,9 @@ export class AlertPolicyServiceClient { * The client will no longer be usable and all future behavior is undefined. */ close(): Promise { + this.initialize(); if (!this._terminated) { - return this.alertPolicyServiceStub.then(stub => { + return this.alertPolicyServiceStub!.then(stub => { this._terminated = true; stub.close(); }); diff --git a/baselines/monitoring/src/v3/group_service_client.ts.baseline b/baselines/monitoring/src/v3/group_service_client.ts.baseline index dd057c86e..03eceac6a 100644 --- a/baselines/monitoring/src/v3/group_service_client.ts.baseline +++ b/baselines/monitoring/src/v3/group_service_client.ts.baseline @@ -47,8 +47,13 @@ export class GroupServiceClient { private _innerApiCalls: {[name: string]: Function}; private _pathTemplates: {[name: string]: gax.PathTemplate}; private _terminated = false; + private _opts: ClientOptions; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; auth: gax.GoogleAuth; - groupServiceStub: Promise<{[name: string]: Function}>; + groupServiceStub?: Promise<{[name: string]: Function}>; /** * Construct an instance of GroupServiceClient. @@ -101,28 +106,31 @@ export class GroupServiceClient { // If we are in browser, we are already using fallback because of the // "browser" field in package.json. // But if we were explicitly requested to use fallback, let's do it now. - const gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; + this._gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; // Create a `gaxGrpc` object, with any grpc-specific options // sent to the client. opts.scopes = (this.constructor as typeof GroupServiceClient).scopes; - const gaxGrpc = new gaxModule.GrpcClient(opts); + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (gaxGrpc.auth as gax.GoogleAuth); + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); // Determine the client header string. const clientHeader = [ - `gax/${gaxModule.version}`, + `gax/${this._gaxModule.version}`, `gapic/${version}`, ]; if (typeof process !== 'undefined' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { - clientHeader.push(`gl-web/${gaxModule.version}`); + clientHeader.push(`gl-web/${this._gaxModule.version}`); } if (!opts.fallback) { - clientHeader.push(`grpc/${gaxGrpc.grpcVersion}`); + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { clientHeader.push(`${opts.libName}/${opts.libVersion}`); @@ -132,7 +140,7 @@ export class GroupServiceClient { // For browsers, pass the JSON content. const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); - const protos = gaxGrpc.loadProto( + this._protos = this._gaxGrpc.loadProto( opts.fallback ? require("../../protos/protos.json") : nodejsProtoPath @@ -142,76 +150,76 @@ export class GroupServiceClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this._pathTemplates = { - folderAlertPolicyPathTemplate: new gaxModule.PathTemplate( + folderAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/alertPolicies/{alert_policy}' ), - folderAlertPolicyConditionPathTemplate: new gaxModule.PathTemplate( + folderAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}' ), - folderChannelDescriptorPathTemplate: new gaxModule.PathTemplate( + folderChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}' ), - folderGroupPathTemplate: new gaxModule.PathTemplate( + folderGroupPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/groups/{group}' ), - folderNotificationChannelPathTemplate: new gaxModule.PathTemplate( + folderNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/notificationChannels/{notification_channel}' ), - folderServicePathTemplate: new gaxModule.PathTemplate( + folderServicePathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/services/{service}' ), - folderServiceServiceLevelObjectivePathTemplate: new gaxModule.PathTemplate( + folderServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}' ), - folderUptimeCheckConfigPathTemplate: new gaxModule.PathTemplate( + folderUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}' ), - organizationAlertPolicyPathTemplate: new gaxModule.PathTemplate( + organizationAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/alertPolicies/{alert_policy}' ), - organizationAlertPolicyConditionPathTemplate: new gaxModule.PathTemplate( + organizationAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}' ), - organizationChannelDescriptorPathTemplate: new gaxModule.PathTemplate( + organizationChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}' ), - organizationGroupPathTemplate: new gaxModule.PathTemplate( + organizationGroupPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/groups/{group}' ), - organizationNotificationChannelPathTemplate: new gaxModule.PathTemplate( + organizationNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/notificationChannels/{notification_channel}' ), - organizationServicePathTemplate: new gaxModule.PathTemplate( + organizationServicePathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/services/{service}' ), - organizationServiceServiceLevelObjectivePathTemplate: new gaxModule.PathTemplate( + organizationServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}' ), - organizationUptimeCheckConfigPathTemplate: new gaxModule.PathTemplate( + organizationUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}' ), - projectAlertPolicyPathTemplate: new gaxModule.PathTemplate( + projectAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/alertPolicies/{alert_policy}' ), - projectAlertPolicyConditionPathTemplate: new gaxModule.PathTemplate( + projectAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}' ), - projectChannelDescriptorPathTemplate: new gaxModule.PathTemplate( + projectChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}' ), - projectGroupPathTemplate: new gaxModule.PathTemplate( + projectGroupPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/groups/{group}' ), - projectNotificationChannelPathTemplate: new gaxModule.PathTemplate( + projectNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/notificationChannels/{notification_channel}' ), - projectServicePathTemplate: new gaxModule.PathTemplate( + projectServicePathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/services/{service}' ), - projectServiceServiceLevelObjectivePathTemplate: new gaxModule.PathTemplate( + projectServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}' ), - projectUptimeCheckConfigPathTemplate: new gaxModule.PathTemplate( + projectUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}' ), }; @@ -221,13 +229,13 @@ export class GroupServiceClient { // pages). Denote the keys used for pagination and results. this._descriptors.page = { listGroups: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'group'), + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'group'), listGroupMembers: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'members') + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'members') }; // Put together the default options sent with requests. - const defaults = gaxGrpc.constructSettings( + this._defaults = this._gaxGrpc.constructSettings( 'google.monitoring.v3.GroupService', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); @@ -235,15 +243,33 @@ export class GroupServiceClient { // of calling the API is handled in `google-gax`, with this code // merely providing the destination and request information. this._innerApiCalls = {}; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.groupServiceStub) { + return this.groupServiceStub; + } // Put together the "service stub" for // google.monitoring.v3.GroupService. - this.groupServiceStub = gaxGrpc.createStub( - opts.fallback ? - (protos as protobuf.Root).lookupService('google.monitoring.v3.GroupService') : + this.groupServiceStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.monitoring.v3.GroupService') : // tslint:disable-next-line no-any - (protos as any).google.monitoring.v3.GroupService, - opts) as Promise<{[method: string]: Function}>; + (this._protos as any).google.monitoring.v3.GroupService, + this._opts) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -262,9 +288,9 @@ export class GroupServiceClient { throw err; }); - const apiCall = gaxModule.createApiCall( + const apiCall = this._gaxModule.createApiCall( innerCallPromise, - defaults[methodName], + this._defaults[methodName], this._descriptors.page[methodName] || this._descriptors.stream[methodName] || this._descriptors.longrunning[methodName] @@ -278,6 +304,8 @@ export class GroupServiceClient { return apiCall(argument, callOptions, callback); }; } + + return this.groupServiceStub; } /** @@ -391,6 +419,7 @@ export class GroupServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.getGroup(request, options, callback); } createGroup( @@ -456,6 +485,7 @@ export class GroupServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.createGroup(request, options, callback); } updateGroup( @@ -519,6 +549,7 @@ export class GroupServiceClient { ] = gax.routingHeader.fromParams({ 'group.name': request.group!.name || '', }); + this.initialize(); return this._innerApiCalls.updateGroup(request, options, callback); } deleteGroup( @@ -583,6 +614,7 @@ export class GroupServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.deleteGroup(request, options, callback); } @@ -680,6 +712,7 @@ export class GroupServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.listGroups(request, options, callback); } @@ -741,6 +774,7 @@ export class GroupServiceClient { 'name': request.name || '', }); const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listGroups.createStream( this._innerApiCalls.listGroups as gax.GaxCall, request, @@ -839,6 +873,7 @@ export class GroupServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.listGroupMembers(request, options, callback); } @@ -898,6 +933,7 @@ export class GroupServiceClient { 'name': request.name || '', }); const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listGroupMembers.createStream( this._innerApiCalls.listGroupMembers as gax.GaxCall, request, @@ -1856,8 +1892,9 @@ export class GroupServiceClient { * The client will no longer be usable and all future behavior is undefined. */ close(): Promise { + this.initialize(); if (!this._terminated) { - return this.groupServiceStub.then(stub => { + return this.groupServiceStub!.then(stub => { this._terminated = true; stub.close(); }); diff --git a/baselines/monitoring/src/v3/metric_service_client.ts.baseline b/baselines/monitoring/src/v3/metric_service_client.ts.baseline index 15bf8586a..2bf394d26 100644 --- a/baselines/monitoring/src/v3/metric_service_client.ts.baseline +++ b/baselines/monitoring/src/v3/metric_service_client.ts.baseline @@ -37,8 +37,13 @@ export class MetricServiceClient { private _innerApiCalls: {[name: string]: Function}; private _pathTemplates: {[name: string]: gax.PathTemplate}; private _terminated = false; + private _opts: ClientOptions; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; auth: gax.GoogleAuth; - metricServiceStub: Promise<{[name: string]: Function}>; + metricServiceStub?: Promise<{[name: string]: Function}>; /** * Construct an instance of MetricServiceClient. @@ -91,28 +96,31 @@ export class MetricServiceClient { // If we are in browser, we are already using fallback because of the // "browser" field in package.json. // But if we were explicitly requested to use fallback, let's do it now. - const gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; + this._gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; // Create a `gaxGrpc` object, with any grpc-specific options // sent to the client. opts.scopes = (this.constructor as typeof MetricServiceClient).scopes; - const gaxGrpc = new gaxModule.GrpcClient(opts); + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (gaxGrpc.auth as gax.GoogleAuth); + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); // Determine the client header string. const clientHeader = [ - `gax/${gaxModule.version}`, + `gax/${this._gaxModule.version}`, `gapic/${version}`, ]; if (typeof process !== 'undefined' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { - clientHeader.push(`gl-web/${gaxModule.version}`); + clientHeader.push(`gl-web/${this._gaxModule.version}`); } if (!opts.fallback) { - clientHeader.push(`grpc/${gaxGrpc.grpcVersion}`); + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { clientHeader.push(`${opts.libName}/${opts.libVersion}`); @@ -122,7 +130,7 @@ export class MetricServiceClient { // For browsers, pass the JSON content. const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); - const protos = gaxGrpc.loadProto( + this._protos = this._gaxGrpc.loadProto( opts.fallback ? require("../../protos/protos.json") : nodejsProtoPath @@ -132,94 +140,94 @@ export class MetricServiceClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this._pathTemplates = { - folderAlertPolicyPathTemplate: new gaxModule.PathTemplate( + folderAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/alertPolicies/{alert_policy}' ), - folderAlertPolicyConditionPathTemplate: new gaxModule.PathTemplate( + folderAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}' ), - folderChannelDescriptorPathTemplate: new gaxModule.PathTemplate( + folderChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}' ), - folderGroupPathTemplate: new gaxModule.PathTemplate( + folderGroupPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/groups/{group}' ), - folderMetricDescriptorPathTemplate: new gaxModule.PathTemplate( + folderMetricDescriptorPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/metricDescriptors/{metric_descriptor=**}' ), - folderMonitoredResourceDescriptorPathTemplate: new gaxModule.PathTemplate( + folderMonitoredResourceDescriptorPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/monitoredResourceDescriptors/{monitored_resource_descriptor}' ), - folderNotificationChannelPathTemplate: new gaxModule.PathTemplate( + folderNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/notificationChannels/{notification_channel}' ), - folderServicePathTemplate: new gaxModule.PathTemplate( + folderServicePathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/services/{service}' ), - folderServiceServiceLevelObjectivePathTemplate: new gaxModule.PathTemplate( + folderServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}' ), - folderUptimeCheckConfigPathTemplate: new gaxModule.PathTemplate( + folderUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}' ), - organizationAlertPolicyPathTemplate: new gaxModule.PathTemplate( + organizationAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/alertPolicies/{alert_policy}' ), - organizationAlertPolicyConditionPathTemplate: new gaxModule.PathTemplate( + organizationAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}' ), - organizationChannelDescriptorPathTemplate: new gaxModule.PathTemplate( + organizationChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}' ), - organizationGroupPathTemplate: new gaxModule.PathTemplate( + organizationGroupPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/groups/{group}' ), - organizationMetricDescriptorPathTemplate: new gaxModule.PathTemplate( + organizationMetricDescriptorPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/metricDescriptors/{metric_descriptor=**}' ), - organizationMonitoredResourceDescriptorPathTemplate: new gaxModule.PathTemplate( + organizationMonitoredResourceDescriptorPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/monitoredResourceDescriptors/{monitored_resource_descriptor}' ), - organizationNotificationChannelPathTemplate: new gaxModule.PathTemplate( + organizationNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/notificationChannels/{notification_channel}' ), - organizationServicePathTemplate: new gaxModule.PathTemplate( + organizationServicePathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/services/{service}' ), - organizationServiceServiceLevelObjectivePathTemplate: new gaxModule.PathTemplate( + organizationServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}' ), - organizationUptimeCheckConfigPathTemplate: new gaxModule.PathTemplate( + organizationUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}' ), - projectAlertPolicyPathTemplate: new gaxModule.PathTemplate( + projectAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/alertPolicies/{alert_policy}' ), - projectAlertPolicyConditionPathTemplate: new gaxModule.PathTemplate( + projectAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}' ), - projectChannelDescriptorPathTemplate: new gaxModule.PathTemplate( + projectChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}' ), - projectGroupPathTemplate: new gaxModule.PathTemplate( + projectGroupPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/groups/{group}' ), - projectMetricDescriptorPathTemplate: new gaxModule.PathTemplate( + projectMetricDescriptorPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/metricDescriptors/{metric_descriptor=**}' ), - projectMonitoredResourceDescriptorPathTemplate: new gaxModule.PathTemplate( + projectMonitoredResourceDescriptorPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/monitoredResourceDescriptors/{monitored_resource_descriptor}' ), - projectNotificationChannelPathTemplate: new gaxModule.PathTemplate( + projectNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/notificationChannels/{notification_channel}' ), - projectServicePathTemplate: new gaxModule.PathTemplate( + projectServicePathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/services/{service}' ), - projectServiceServiceLevelObjectivePathTemplate: new gaxModule.PathTemplate( + projectServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}' ), - projectUptimeCheckConfigPathTemplate: new gaxModule.PathTemplate( + projectUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}' ), }; @@ -229,15 +237,15 @@ export class MetricServiceClient { // pages). Denote the keys used for pagination and results. this._descriptors.page = { listMonitoredResourceDescriptors: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'resourceDescriptors'), + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'resourceDescriptors'), listMetricDescriptors: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'metricDescriptors'), + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'metricDescriptors'), listTimeSeries: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'timeSeries') + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'timeSeries') }; // Put together the default options sent with requests. - const defaults = gaxGrpc.constructSettings( + this._defaults = this._gaxGrpc.constructSettings( 'google.monitoring.v3.MetricService', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); @@ -245,15 +253,33 @@ export class MetricServiceClient { // of calling the API is handled in `google-gax`, with this code // merely providing the destination and request information. this._innerApiCalls = {}; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.metricServiceStub) { + return this.metricServiceStub; + } // Put together the "service stub" for // google.monitoring.v3.MetricService. - this.metricServiceStub = gaxGrpc.createStub( - opts.fallback ? - (protos as protobuf.Root).lookupService('google.monitoring.v3.MetricService') : + this.metricServiceStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.monitoring.v3.MetricService') : // tslint:disable-next-line no-any - (protos as any).google.monitoring.v3.MetricService, - opts) as Promise<{[method: string]: Function}>; + (this._protos as any).google.monitoring.v3.MetricService, + this._opts) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -272,9 +298,9 @@ export class MetricServiceClient { throw err; }); - const apiCall = gaxModule.createApiCall( + const apiCall = this._gaxModule.createApiCall( innerCallPromise, - defaults[methodName], + this._defaults[methodName], this._descriptors.page[methodName] || this._descriptors.stream[methodName] || this._descriptors.longrunning[methodName] @@ -288,6 +314,8 @@ export class MetricServiceClient { return apiCall(argument, callOptions, callback); }; } + + return this.metricServiceStub; } /** @@ -404,6 +432,7 @@ export class MetricServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.getMonitoredResourceDescriptor(request, options, callback); } getMetricDescriptor( @@ -466,6 +495,7 @@ export class MetricServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.getMetricDescriptor(request, options, callback); } createMetricDescriptor( @@ -531,6 +561,7 @@ export class MetricServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.createMetricDescriptor(request, options, callback); } deleteMetricDescriptor( @@ -594,6 +625,7 @@ export class MetricServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.deleteMetricDescriptor(request, options, callback); } createTimeSeries( @@ -665,6 +697,7 @@ export class MetricServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.createTimeSeries(request, options, callback); } @@ -755,6 +788,7 @@ export class MetricServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.listMonitoredResourceDescriptors(request, options, callback); } @@ -809,6 +843,7 @@ export class MetricServiceClient { 'name': request.name || '', }); const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listMonitoredResourceDescriptors.createStream( this._innerApiCalls.listMonitoredResourceDescriptors as gax.GaxCall, request, @@ -903,6 +938,7 @@ export class MetricServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.listMetricDescriptors(request, options, callback); } @@ -958,6 +994,7 @@ export class MetricServiceClient { 'name': request.name || '', }); const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listMetricDescriptors.createStream( this._innerApiCalls.listMetricDescriptors as gax.GaxCall, request, @@ -1070,6 +1107,7 @@ export class MetricServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.listTimeSeries(request, options, callback); } @@ -1143,6 +1181,7 @@ export class MetricServiceClient { 'name': request.name || '', }); const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listTimeSeries.createStream( this._innerApiCalls.listTimeSeries as gax.GaxCall, request, @@ -2317,8 +2356,9 @@ export class MetricServiceClient { * The client will no longer be usable and all future behavior is undefined. */ close(): Promise { + this.initialize(); if (!this._terminated) { - return this.metricServiceStub.then(stub => { + return this.metricServiceStub!.then(stub => { this._terminated = true; stub.close(); }); diff --git a/baselines/monitoring/src/v3/notification_channel_service_client.ts.baseline b/baselines/monitoring/src/v3/notification_channel_service_client.ts.baseline index 6cbd0a859..fd20fd543 100644 --- a/baselines/monitoring/src/v3/notification_channel_service_client.ts.baseline +++ b/baselines/monitoring/src/v3/notification_channel_service_client.ts.baseline @@ -37,8 +37,13 @@ export class NotificationChannelServiceClient { private _innerApiCalls: {[name: string]: Function}; private _pathTemplates: {[name: string]: gax.PathTemplate}; private _terminated = false; + private _opts: ClientOptions; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; auth: gax.GoogleAuth; - notificationChannelServiceStub: Promise<{[name: string]: Function}>; + notificationChannelServiceStub?: Promise<{[name: string]: Function}>; /** * Construct an instance of NotificationChannelServiceClient. @@ -91,28 +96,31 @@ export class NotificationChannelServiceClient { // If we are in browser, we are already using fallback because of the // "browser" field in package.json. // But if we were explicitly requested to use fallback, let's do it now. - const gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; + this._gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; // Create a `gaxGrpc` object, with any grpc-specific options // sent to the client. opts.scopes = (this.constructor as typeof NotificationChannelServiceClient).scopes; - const gaxGrpc = new gaxModule.GrpcClient(opts); + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (gaxGrpc.auth as gax.GoogleAuth); + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); // Determine the client header string. const clientHeader = [ - `gax/${gaxModule.version}`, + `gax/${this._gaxModule.version}`, `gapic/${version}`, ]; if (typeof process !== 'undefined' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { - clientHeader.push(`gl-web/${gaxModule.version}`); + clientHeader.push(`gl-web/${this._gaxModule.version}`); } if (!opts.fallback) { - clientHeader.push(`grpc/${gaxGrpc.grpcVersion}`); + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { clientHeader.push(`${opts.libName}/${opts.libVersion}`); @@ -122,7 +130,7 @@ export class NotificationChannelServiceClient { // For browsers, pass the JSON content. const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); - const protos = gaxGrpc.loadProto( + this._protos = this._gaxGrpc.loadProto( opts.fallback ? require("../../protos/protos.json") : nodejsProtoPath @@ -132,76 +140,76 @@ export class NotificationChannelServiceClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this._pathTemplates = { - folderAlertPolicyPathTemplate: new gaxModule.PathTemplate( + folderAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/alertPolicies/{alert_policy}' ), - folderAlertPolicyConditionPathTemplate: new gaxModule.PathTemplate( + folderAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}' ), - folderChannelDescriptorPathTemplate: new gaxModule.PathTemplate( + folderChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}' ), - folderGroupPathTemplate: new gaxModule.PathTemplate( + folderGroupPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/groups/{group}' ), - folderNotificationChannelPathTemplate: new gaxModule.PathTemplate( + folderNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/notificationChannels/{notification_channel}' ), - folderServicePathTemplate: new gaxModule.PathTemplate( + folderServicePathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/services/{service}' ), - folderServiceServiceLevelObjectivePathTemplate: new gaxModule.PathTemplate( + folderServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}' ), - folderUptimeCheckConfigPathTemplate: new gaxModule.PathTemplate( + folderUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}' ), - organizationAlertPolicyPathTemplate: new gaxModule.PathTemplate( + organizationAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/alertPolicies/{alert_policy}' ), - organizationAlertPolicyConditionPathTemplate: new gaxModule.PathTemplate( + organizationAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}' ), - organizationChannelDescriptorPathTemplate: new gaxModule.PathTemplate( + organizationChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}' ), - organizationGroupPathTemplate: new gaxModule.PathTemplate( + organizationGroupPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/groups/{group}' ), - organizationNotificationChannelPathTemplate: new gaxModule.PathTemplate( + organizationNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/notificationChannels/{notification_channel}' ), - organizationServicePathTemplate: new gaxModule.PathTemplate( + organizationServicePathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/services/{service}' ), - organizationServiceServiceLevelObjectivePathTemplate: new gaxModule.PathTemplate( + organizationServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}' ), - organizationUptimeCheckConfigPathTemplate: new gaxModule.PathTemplate( + organizationUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}' ), - projectAlertPolicyPathTemplate: new gaxModule.PathTemplate( + projectAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/alertPolicies/{alert_policy}' ), - projectAlertPolicyConditionPathTemplate: new gaxModule.PathTemplate( + projectAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}' ), - projectChannelDescriptorPathTemplate: new gaxModule.PathTemplate( + projectChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}' ), - projectGroupPathTemplate: new gaxModule.PathTemplate( + projectGroupPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/groups/{group}' ), - projectNotificationChannelPathTemplate: new gaxModule.PathTemplate( + projectNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/notificationChannels/{notification_channel}' ), - projectServicePathTemplate: new gaxModule.PathTemplate( + projectServicePathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/services/{service}' ), - projectServiceServiceLevelObjectivePathTemplate: new gaxModule.PathTemplate( + projectServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}' ), - projectUptimeCheckConfigPathTemplate: new gaxModule.PathTemplate( + projectUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}' ), }; @@ -211,13 +219,13 @@ export class NotificationChannelServiceClient { // pages). Denote the keys used for pagination and results. this._descriptors.page = { listNotificationChannelDescriptors: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'channelDescriptors'), + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'channelDescriptors'), listNotificationChannels: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'notificationChannels') + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'notificationChannels') }; // Put together the default options sent with requests. - const defaults = gaxGrpc.constructSettings( + this._defaults = this._gaxGrpc.constructSettings( 'google.monitoring.v3.NotificationChannelService', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); @@ -225,15 +233,33 @@ export class NotificationChannelServiceClient { // of calling the API is handled in `google-gax`, with this code // merely providing the destination and request information. this._innerApiCalls = {}; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.notificationChannelServiceStub) { + return this.notificationChannelServiceStub; + } // Put together the "service stub" for // google.monitoring.v3.NotificationChannelService. - this.notificationChannelServiceStub = gaxGrpc.createStub( - opts.fallback ? - (protos as protobuf.Root).lookupService('google.monitoring.v3.NotificationChannelService') : + this.notificationChannelServiceStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.monitoring.v3.NotificationChannelService') : // tslint:disable-next-line no-any - (protos as any).google.monitoring.v3.NotificationChannelService, - opts) as Promise<{[method: string]: Function}>; + (this._protos as any).google.monitoring.v3.NotificationChannelService, + this._opts) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -252,9 +278,9 @@ export class NotificationChannelServiceClient { throw err; }); - const apiCall = gaxModule.createApiCall( + const apiCall = this._gaxModule.createApiCall( innerCallPromise, - defaults[methodName], + this._defaults[methodName], this._descriptors.page[methodName] || this._descriptors.stream[methodName] || this._descriptors.longrunning[methodName] @@ -268,6 +294,8 @@ export class NotificationChannelServiceClient { return apiCall(argument, callOptions, callback); }; } + + return this.notificationChannelServiceStub; } /** @@ -382,6 +410,7 @@ export class NotificationChannelServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.getNotificationChannelDescriptor(request, options, callback); } getNotificationChannel( @@ -446,6 +475,7 @@ export class NotificationChannelServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.getNotificationChannel(request, options, callback); } createNotificationChannel( @@ -515,6 +545,7 @@ export class NotificationChannelServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.createNotificationChannel(request, options, callback); } updateNotificationChannel( @@ -580,6 +611,7 @@ export class NotificationChannelServiceClient { ] = gax.routingHeader.fromParams({ 'notification_channel.name': request.notificationChannel!.name || '', }); + this.initialize(); return this._innerApiCalls.updateNotificationChannel(request, options, callback); } deleteNotificationChannel( @@ -645,6 +677,7 @@ export class NotificationChannelServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.deleteNotificationChannel(request, options, callback); } sendNotificationChannelVerificationCode( @@ -705,6 +738,7 @@ export class NotificationChannelServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.sendNotificationChannelVerificationCode(request, options, callback); } getNotificationChannelVerificationCode( @@ -796,6 +830,7 @@ export class NotificationChannelServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.getNotificationChannelVerificationCode(request, options, callback); } verifyNotificationChannel( @@ -865,6 +900,7 @@ export class NotificationChannelServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.verifyNotificationChannel(request, options, callback); } @@ -957,6 +993,7 @@ export class NotificationChannelServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.listNotificationChannelDescriptors(request, options, callback); } @@ -1012,6 +1049,7 @@ export class NotificationChannelServiceClient { 'name': request.name || '', }); const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listNotificationChannelDescriptors.createStream( this._innerApiCalls.listNotificationChannelDescriptors as gax.GaxCall, request, @@ -1117,6 +1155,7 @@ export class NotificationChannelServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.listNotificationChannels(request, options, callback); } @@ -1183,6 +1222,7 @@ export class NotificationChannelServiceClient { 'name': request.name || '', }); const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listNotificationChannels.createStream( this._innerApiCalls.listNotificationChannels as gax.GaxCall, request, @@ -2141,8 +2181,9 @@ export class NotificationChannelServiceClient { * The client will no longer be usable and all future behavior is undefined. */ close(): Promise { + this.initialize(); if (!this._terminated) { - return this.notificationChannelServiceStub.then(stub => { + return this.notificationChannelServiceStub!.then(stub => { this._terminated = true; stub.close(); }); diff --git a/baselines/monitoring/src/v3/service_monitoring_service_client.ts.baseline b/baselines/monitoring/src/v3/service_monitoring_service_client.ts.baseline index b0f487f74..3212c34b0 100644 --- a/baselines/monitoring/src/v3/service_monitoring_service_client.ts.baseline +++ b/baselines/monitoring/src/v3/service_monitoring_service_client.ts.baseline @@ -39,8 +39,13 @@ export class ServiceMonitoringServiceClient { private _innerApiCalls: {[name: string]: Function}; private _pathTemplates: {[name: string]: gax.PathTemplate}; private _terminated = false; + private _opts: ClientOptions; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; auth: gax.GoogleAuth; - serviceMonitoringServiceStub: Promise<{[name: string]: Function}>; + serviceMonitoringServiceStub?: Promise<{[name: string]: Function}>; /** * Construct an instance of ServiceMonitoringServiceClient. @@ -93,28 +98,31 @@ export class ServiceMonitoringServiceClient { // If we are in browser, we are already using fallback because of the // "browser" field in package.json. // But if we were explicitly requested to use fallback, let's do it now. - const gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; + this._gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; // Create a `gaxGrpc` object, with any grpc-specific options // sent to the client. opts.scopes = (this.constructor as typeof ServiceMonitoringServiceClient).scopes; - const gaxGrpc = new gaxModule.GrpcClient(opts); + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (gaxGrpc.auth as gax.GoogleAuth); + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); // Determine the client header string. const clientHeader = [ - `gax/${gaxModule.version}`, + `gax/${this._gaxModule.version}`, `gapic/${version}`, ]; if (typeof process !== 'undefined' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { - clientHeader.push(`gl-web/${gaxModule.version}`); + clientHeader.push(`gl-web/${this._gaxModule.version}`); } if (!opts.fallback) { - clientHeader.push(`grpc/${gaxGrpc.grpcVersion}`); + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { clientHeader.push(`${opts.libName}/${opts.libVersion}`); @@ -124,7 +132,7 @@ export class ServiceMonitoringServiceClient { // For browsers, pass the JSON content. const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); - const protos = gaxGrpc.loadProto( + this._protos = this._gaxGrpc.loadProto( opts.fallback ? require("../../protos/protos.json") : nodejsProtoPath @@ -134,76 +142,76 @@ export class ServiceMonitoringServiceClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this._pathTemplates = { - folderAlertPolicyPathTemplate: new gaxModule.PathTemplate( + folderAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/alertPolicies/{alert_policy}' ), - folderAlertPolicyConditionPathTemplate: new gaxModule.PathTemplate( + folderAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}' ), - folderChannelDescriptorPathTemplate: new gaxModule.PathTemplate( + folderChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}' ), - folderGroupPathTemplate: new gaxModule.PathTemplate( + folderGroupPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/groups/{group}' ), - folderNotificationChannelPathTemplate: new gaxModule.PathTemplate( + folderNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/notificationChannels/{notification_channel}' ), - folderServicePathTemplate: new gaxModule.PathTemplate( + folderServicePathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/services/{service}' ), - folderServiceServiceLevelObjectivePathTemplate: new gaxModule.PathTemplate( + folderServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}' ), - folderUptimeCheckConfigPathTemplate: new gaxModule.PathTemplate( + folderUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}' ), - organizationAlertPolicyPathTemplate: new gaxModule.PathTemplate( + organizationAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/alertPolicies/{alert_policy}' ), - organizationAlertPolicyConditionPathTemplate: new gaxModule.PathTemplate( + organizationAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}' ), - organizationChannelDescriptorPathTemplate: new gaxModule.PathTemplate( + organizationChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}' ), - organizationGroupPathTemplate: new gaxModule.PathTemplate( + organizationGroupPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/groups/{group}' ), - organizationNotificationChannelPathTemplate: new gaxModule.PathTemplate( + organizationNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/notificationChannels/{notification_channel}' ), - organizationServicePathTemplate: new gaxModule.PathTemplate( + organizationServicePathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/services/{service}' ), - organizationServiceServiceLevelObjectivePathTemplate: new gaxModule.PathTemplate( + organizationServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}' ), - organizationUptimeCheckConfigPathTemplate: new gaxModule.PathTemplate( + organizationUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}' ), - projectAlertPolicyPathTemplate: new gaxModule.PathTemplate( + projectAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/alertPolicies/{alert_policy}' ), - projectAlertPolicyConditionPathTemplate: new gaxModule.PathTemplate( + projectAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}' ), - projectChannelDescriptorPathTemplate: new gaxModule.PathTemplate( + projectChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}' ), - projectGroupPathTemplate: new gaxModule.PathTemplate( + projectGroupPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/groups/{group}' ), - projectNotificationChannelPathTemplate: new gaxModule.PathTemplate( + projectNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/notificationChannels/{notification_channel}' ), - projectServicePathTemplate: new gaxModule.PathTemplate( + projectServicePathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/services/{service}' ), - projectServiceServiceLevelObjectivePathTemplate: new gaxModule.PathTemplate( + projectServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}' ), - projectUptimeCheckConfigPathTemplate: new gaxModule.PathTemplate( + projectUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}' ), }; @@ -213,13 +221,13 @@ export class ServiceMonitoringServiceClient { // pages). Denote the keys used for pagination and results. this._descriptors.page = { listServices: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'services'), + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'services'), listServiceLevelObjectives: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'serviceLevelObjectives') + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'serviceLevelObjectives') }; // Put together the default options sent with requests. - const defaults = gaxGrpc.constructSettings( + this._defaults = this._gaxGrpc.constructSettings( 'google.monitoring.v3.ServiceMonitoringService', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); @@ -227,15 +235,33 @@ export class ServiceMonitoringServiceClient { // of calling the API is handled in `google-gax`, with this code // merely providing the destination and request information. this._innerApiCalls = {}; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.serviceMonitoringServiceStub) { + return this.serviceMonitoringServiceStub; + } // Put together the "service stub" for // google.monitoring.v3.ServiceMonitoringService. - this.serviceMonitoringServiceStub = gaxGrpc.createStub( - opts.fallback ? - (protos as protobuf.Root).lookupService('google.monitoring.v3.ServiceMonitoringService') : + this.serviceMonitoringServiceStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.monitoring.v3.ServiceMonitoringService') : // tslint:disable-next-line no-any - (protos as any).google.monitoring.v3.ServiceMonitoringService, - opts) as Promise<{[method: string]: Function}>; + (this._protos as any).google.monitoring.v3.ServiceMonitoringService, + this._opts) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -254,9 +280,9 @@ export class ServiceMonitoringServiceClient { throw err; }); - const apiCall = gaxModule.createApiCall( + const apiCall = this._gaxModule.createApiCall( innerCallPromise, - defaults[methodName], + this._defaults[methodName], this._descriptors.page[methodName] || this._descriptors.stream[methodName] || this._descriptors.longrunning[methodName] @@ -270,6 +296,8 @@ export class ServiceMonitoringServiceClient { return apiCall(argument, callOptions, callback); }; } + + return this.serviceMonitoringServiceStub; } /** @@ -388,6 +416,7 @@ export class ServiceMonitoringServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.createService(request, options, callback); } getService( @@ -448,6 +477,7 @@ export class ServiceMonitoringServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.getService(request, options, callback); } updateService( @@ -510,6 +540,7 @@ export class ServiceMonitoringServiceClient { ] = gax.routingHeader.fromParams({ 'service.name': request.service!.name || '', }); + this.initialize(); return this._innerApiCalls.updateService(request, options, callback); } deleteService( @@ -570,6 +601,7 @@ export class ServiceMonitoringServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.deleteService(request, options, callback); } createServiceLevelObjective( @@ -638,6 +670,7 @@ export class ServiceMonitoringServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.createServiceLevelObjective(request, options, callback); } getServiceLevelObjective( @@ -704,6 +737,7 @@ export class ServiceMonitoringServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.getServiceLevelObjective(request, options, callback); } updateServiceLevelObjective( @@ -766,6 +800,7 @@ export class ServiceMonitoringServiceClient { ] = gax.routingHeader.fromParams({ 'service_level_objective.name': request.serviceLevelObjective!.name || '', }); + this.initialize(); return this._innerApiCalls.updateServiceLevelObjective(request, options, callback); } deleteServiceLevelObjective( @@ -827,6 +862,7 @@ export class ServiceMonitoringServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.deleteServiceLevelObjective(request, options, callback); } @@ -926,6 +962,7 @@ export class ServiceMonitoringServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.listServices(request, options, callback); } @@ -989,6 +1026,7 @@ export class ServiceMonitoringServiceClient { 'parent': request.parent || '', }); const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listServices.createStream( this._innerApiCalls.listServices as gax.GaxCall, request, @@ -1082,6 +1120,7 @@ export class ServiceMonitoringServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.listServiceLevelObjectives(request, options, callback); } @@ -1136,6 +1175,7 @@ export class ServiceMonitoringServiceClient { 'parent': request.parent || '', }); const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listServiceLevelObjectives.createStream( this._innerApiCalls.listServiceLevelObjectives as gax.GaxCall, request, @@ -2094,8 +2134,9 @@ export class ServiceMonitoringServiceClient { * The client will no longer be usable and all future behavior is undefined. */ close(): Promise { + this.initialize(); if (!this._terminated) { - return this.serviceMonitoringServiceStub.then(stub => { + return this.serviceMonitoringServiceStub!.then(stub => { this._terminated = true; stub.close(); }); diff --git a/baselines/monitoring/src/v3/uptime_check_service_client.ts.baseline b/baselines/monitoring/src/v3/uptime_check_service_client.ts.baseline index 2e5537f54..c97f00585 100644 --- a/baselines/monitoring/src/v3/uptime_check_service_client.ts.baseline +++ b/baselines/monitoring/src/v3/uptime_check_service_client.ts.baseline @@ -43,8 +43,13 @@ export class UptimeCheckServiceClient { private _innerApiCalls: {[name: string]: Function}; private _pathTemplates: {[name: string]: gax.PathTemplate}; private _terminated = false; + private _opts: ClientOptions; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; auth: gax.GoogleAuth; - uptimeCheckServiceStub: Promise<{[name: string]: Function}>; + uptimeCheckServiceStub?: Promise<{[name: string]: Function}>; /** * Construct an instance of UptimeCheckServiceClient. @@ -97,28 +102,31 @@ export class UptimeCheckServiceClient { // If we are in browser, we are already using fallback because of the // "browser" field in package.json. // But if we were explicitly requested to use fallback, let's do it now. - const gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; + this._gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; // Create a `gaxGrpc` object, with any grpc-specific options // sent to the client. opts.scopes = (this.constructor as typeof UptimeCheckServiceClient).scopes; - const gaxGrpc = new gaxModule.GrpcClient(opts); + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (gaxGrpc.auth as gax.GoogleAuth); + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); // Determine the client header string. const clientHeader = [ - `gax/${gaxModule.version}`, + `gax/${this._gaxModule.version}`, `gapic/${version}`, ]; if (typeof process !== 'undefined' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { - clientHeader.push(`gl-web/${gaxModule.version}`); + clientHeader.push(`gl-web/${this._gaxModule.version}`); } if (!opts.fallback) { - clientHeader.push(`grpc/${gaxGrpc.grpcVersion}`); + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { clientHeader.push(`${opts.libName}/${opts.libVersion}`); @@ -128,7 +136,7 @@ export class UptimeCheckServiceClient { // For browsers, pass the JSON content. const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); - const protos = gaxGrpc.loadProto( + this._protos = this._gaxGrpc.loadProto( opts.fallback ? require("../../protos/protos.json") : nodejsProtoPath @@ -138,76 +146,76 @@ export class UptimeCheckServiceClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this._pathTemplates = { - folderAlertPolicyPathTemplate: new gaxModule.PathTemplate( + folderAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/alertPolicies/{alert_policy}' ), - folderAlertPolicyConditionPathTemplate: new gaxModule.PathTemplate( + folderAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/alertPolicies/{alert_policy}/conditions/{condition}' ), - folderChannelDescriptorPathTemplate: new gaxModule.PathTemplate( + folderChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/notificationChannelDescriptors/{channel_descriptor}' ), - folderGroupPathTemplate: new gaxModule.PathTemplate( + folderGroupPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/groups/{group}' ), - folderNotificationChannelPathTemplate: new gaxModule.PathTemplate( + folderNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/notificationChannels/{notification_channel}' ), - folderServicePathTemplate: new gaxModule.PathTemplate( + folderServicePathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/services/{service}' ), - folderServiceServiceLevelObjectivePathTemplate: new gaxModule.PathTemplate( + folderServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/services/{service}/serviceLevelObjectives/{service_level_objective}' ), - folderUptimeCheckConfigPathTemplate: new gaxModule.PathTemplate( + folderUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( 'folders/{folder}/uptimeCheckConfigs/{uptime_check_config}' ), - organizationAlertPolicyPathTemplate: new gaxModule.PathTemplate( + organizationAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/alertPolicies/{alert_policy}' ), - organizationAlertPolicyConditionPathTemplate: new gaxModule.PathTemplate( + organizationAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/alertPolicies/{alert_policy}/conditions/{condition}' ), - organizationChannelDescriptorPathTemplate: new gaxModule.PathTemplate( + organizationChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/notificationChannelDescriptors/{channel_descriptor}' ), - organizationGroupPathTemplate: new gaxModule.PathTemplate( + organizationGroupPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/groups/{group}' ), - organizationNotificationChannelPathTemplate: new gaxModule.PathTemplate( + organizationNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/notificationChannels/{notification_channel}' ), - organizationServicePathTemplate: new gaxModule.PathTemplate( + organizationServicePathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/services/{service}' ), - organizationServiceServiceLevelObjectivePathTemplate: new gaxModule.PathTemplate( + organizationServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/services/{service}/serviceLevelObjectives/{service_level_objective}' ), - organizationUptimeCheckConfigPathTemplate: new gaxModule.PathTemplate( + organizationUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( 'organizations/{organization}/uptimeCheckConfigs/{uptime_check_config}' ), - projectAlertPolicyPathTemplate: new gaxModule.PathTemplate( + projectAlertPolicyPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/alertPolicies/{alert_policy}' ), - projectAlertPolicyConditionPathTemplate: new gaxModule.PathTemplate( + projectAlertPolicyConditionPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}' ), - projectChannelDescriptorPathTemplate: new gaxModule.PathTemplate( + projectChannelDescriptorPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/notificationChannelDescriptors/{channel_descriptor}' ), - projectGroupPathTemplate: new gaxModule.PathTemplate( + projectGroupPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/groups/{group}' ), - projectNotificationChannelPathTemplate: new gaxModule.PathTemplate( + projectNotificationChannelPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/notificationChannels/{notification_channel}' ), - projectServicePathTemplate: new gaxModule.PathTemplate( + projectServicePathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/services/{service}' ), - projectServiceServiceLevelObjectivePathTemplate: new gaxModule.PathTemplate( + projectServiceServiceLevelObjectivePathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/services/{service}/serviceLevelObjectives/{service_level_objective}' ), - projectUptimeCheckConfigPathTemplate: new gaxModule.PathTemplate( + projectUptimeCheckConfigPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/uptimeCheckConfigs/{uptime_check_config}' ), }; @@ -217,13 +225,13 @@ export class UptimeCheckServiceClient { // pages). Denote the keys used for pagination and results. this._descriptors.page = { listUptimeCheckConfigs: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'uptimeCheckConfigs'), + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'uptimeCheckConfigs'), listUptimeCheckIps: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'uptimeCheckIps') + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'uptimeCheckIps') }; // Put together the default options sent with requests. - const defaults = gaxGrpc.constructSettings( + this._defaults = this._gaxGrpc.constructSettings( 'google.monitoring.v3.UptimeCheckService', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); @@ -231,15 +239,33 @@ export class UptimeCheckServiceClient { // of calling the API is handled in `google-gax`, with this code // merely providing the destination and request information. this._innerApiCalls = {}; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.uptimeCheckServiceStub) { + return this.uptimeCheckServiceStub; + } // Put together the "service stub" for // google.monitoring.v3.UptimeCheckService. - this.uptimeCheckServiceStub = gaxGrpc.createStub( - opts.fallback ? - (protos as protobuf.Root).lookupService('google.monitoring.v3.UptimeCheckService') : + this.uptimeCheckServiceStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.monitoring.v3.UptimeCheckService') : // tslint:disable-next-line no-any - (protos as any).google.monitoring.v3.UptimeCheckService, - opts) as Promise<{[method: string]: Function}>; + (this._protos as any).google.monitoring.v3.UptimeCheckService, + this._opts) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -258,9 +284,9 @@ export class UptimeCheckServiceClient { throw err; }); - const apiCall = gaxModule.createApiCall( + const apiCall = this._gaxModule.createApiCall( innerCallPromise, - defaults[methodName], + this._defaults[methodName], this._descriptors.page[methodName] || this._descriptors.stream[methodName] || this._descriptors.longrunning[methodName] @@ -274,6 +300,8 @@ export class UptimeCheckServiceClient { return apiCall(argument, callOptions, callback); }; } + + return this.uptimeCheckServiceStub; } /** @@ -387,6 +415,7 @@ export class UptimeCheckServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.getUptimeCheckConfig(request, options, callback); } createUptimeCheckConfig( @@ -449,6 +478,7 @@ export class UptimeCheckServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.createUptimeCheckConfig(request, options, callback); } updateUptimeCheckConfig( @@ -526,6 +556,7 @@ export class UptimeCheckServiceClient { ] = gax.routingHeader.fromParams({ 'uptime_check_config.name': request.uptimeCheckConfig!.name || '', }); + this.initialize(); return this._innerApiCalls.updateUptimeCheckConfig(request, options, callback); } deleteUptimeCheckConfig( @@ -588,6 +619,7 @@ export class UptimeCheckServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.deleteUptimeCheckConfig(request, options, callback); } @@ -674,6 +706,7 @@ export class UptimeCheckServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.listUptimeCheckConfigs(request, options, callback); } @@ -723,6 +756,7 @@ export class UptimeCheckServiceClient { 'parent': request.parent || '', }); const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listUptimeCheckConfigs.createStream( this._innerApiCalls.listUptimeCheckConfigs as gax.GaxCall, request, @@ -803,6 +837,7 @@ export class UptimeCheckServiceClient { options = optionsOrCallback as gax.CallOptions; } options = options || {}; + this.initialize(); return this._innerApiCalls.listUptimeCheckIps(request, options, callback); } @@ -844,6 +879,7 @@ export class UptimeCheckServiceClient { request = request || {}; options = options || {}; const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listUptimeCheckIps.createStream( this._innerApiCalls.listUptimeCheckIps as gax.GaxCall, request, @@ -1802,8 +1838,9 @@ export class UptimeCheckServiceClient { * The client will no longer be usable and all future behavior is undefined. */ close(): Promise { + this.initialize(); if (!this._terminated) { - return this.uptimeCheckServiceStub.then(stub => { + return this.uptimeCheckServiceStub!.then(stub => { this._terminated = true; stub.close(); }); diff --git a/baselines/monitoring/test/gapic-alert_policy_service-v3.ts.baseline b/baselines/monitoring/test/gapic-alert_policy_service-v3.ts.baseline index 13fa999b8..d819d6c13 100644 --- a/baselines/monitoring/test/gapic-alert_policy_service-v3.ts.baseline +++ b/baselines/monitoring/test/gapic-alert_policy_service-v3.ts.baseline @@ -78,12 +78,30 @@ describe('v3.AlertPolicyServiceClient', () => { }); assert(client); }); + it('has initialize method and supports deferred initialization', async () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.alertPolicyServiceStub, undefined); + await client.initialize(); + assert(client.alertPolicyServiceStub); + }); + it('has close method', () => { + const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.close(); + }); describe('getAlertPolicy', () => { it('invokes getAlertPolicy without error', done => { const client = new alertpolicyserviceModule.v3.AlertPolicyServiceClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IGetAlertPolicyRequest = {}; request.name = ''; @@ -107,6 +125,8 @@ describe('v3.AlertPolicyServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IGetAlertPolicyRequest = {}; request.name = ''; @@ -132,6 +152,8 @@ describe('v3.AlertPolicyServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.ICreateAlertPolicyRequest = {}; request.name = ''; @@ -155,6 +177,8 @@ describe('v3.AlertPolicyServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.ICreateAlertPolicyRequest = {}; request.name = ''; @@ -180,6 +204,8 @@ describe('v3.AlertPolicyServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IDeleteAlertPolicyRequest = {}; request.name = ''; @@ -203,6 +229,8 @@ describe('v3.AlertPolicyServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IDeleteAlertPolicyRequest = {}; request.name = ''; @@ -228,6 +256,8 @@ describe('v3.AlertPolicyServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IUpdateAlertPolicyRequest = {}; request.alertPolicy = {}; @@ -252,6 +282,8 @@ describe('v3.AlertPolicyServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IUpdateAlertPolicyRequest = {}; request.alertPolicy = {}; @@ -278,6 +310,8 @@ describe('v3.AlertPolicyServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IListAlertPoliciesRequest = {}; request.name = ''; @@ -301,6 +335,8 @@ describe('v3.AlertPolicyServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IListAlertPoliciesRequest = {}; request.name = ''; diff --git a/baselines/monitoring/test/gapic-group_service-v3.ts.baseline b/baselines/monitoring/test/gapic-group_service-v3.ts.baseline index df8dfb910..5ce2c4377 100644 --- a/baselines/monitoring/test/gapic-group_service-v3.ts.baseline +++ b/baselines/monitoring/test/gapic-group_service-v3.ts.baseline @@ -78,12 +78,30 @@ describe('v3.GroupServiceClient', () => { }); assert(client); }); + it('has initialize method and supports deferred initialization', async () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.groupServiceStub, undefined); + await client.initialize(); + assert(client.groupServiceStub); + }); + it('has close method', () => { + const client = new groupserviceModule.v3.GroupServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.close(); + }); describe('getGroup', () => { it('invokes getGroup without error', done => { const client = new groupserviceModule.v3.GroupServiceClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IGetGroupRequest = {}; request.name = ''; @@ -107,6 +125,8 @@ describe('v3.GroupServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IGetGroupRequest = {}; request.name = ''; @@ -132,6 +152,8 @@ describe('v3.GroupServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.ICreateGroupRequest = {}; request.name = ''; @@ -155,6 +177,8 @@ describe('v3.GroupServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.ICreateGroupRequest = {}; request.name = ''; @@ -180,6 +204,8 @@ describe('v3.GroupServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IUpdateGroupRequest = {}; request.group = {}; @@ -204,6 +230,8 @@ describe('v3.GroupServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IUpdateGroupRequest = {}; request.group = {}; @@ -230,6 +258,8 @@ describe('v3.GroupServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IDeleteGroupRequest = {}; request.name = ''; @@ -253,6 +283,8 @@ describe('v3.GroupServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IDeleteGroupRequest = {}; request.name = ''; @@ -278,6 +310,8 @@ describe('v3.GroupServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IListGroupsRequest = {}; request.name = ''; @@ -301,6 +335,8 @@ describe('v3.GroupServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IListGroupsRequest = {}; request.name = ''; @@ -326,6 +362,8 @@ describe('v3.GroupServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IListGroupMembersRequest = {}; request.name = ''; @@ -349,6 +387,8 @@ describe('v3.GroupServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IListGroupMembersRequest = {}; request.name = ''; diff --git a/baselines/monitoring/test/gapic-metric_service-v3.ts.baseline b/baselines/monitoring/test/gapic-metric_service-v3.ts.baseline index a709a3212..3ad923e29 100644 --- a/baselines/monitoring/test/gapic-metric_service-v3.ts.baseline +++ b/baselines/monitoring/test/gapic-metric_service-v3.ts.baseline @@ -78,12 +78,30 @@ describe('v3.MetricServiceClient', () => { }); assert(client); }); + it('has initialize method and supports deferred initialization', async () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.metricServiceStub, undefined); + await client.initialize(); + assert(client.metricServiceStub); + }); + it('has close method', () => { + const client = new metricserviceModule.v3.MetricServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.close(); + }); describe('getMonitoredResourceDescriptor', () => { it('invokes getMonitoredResourceDescriptor without error', done => { const client = new metricserviceModule.v3.MetricServiceClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest = {}; request.name = ''; @@ -107,6 +125,8 @@ describe('v3.MetricServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IGetMonitoredResourceDescriptorRequest = {}; request.name = ''; @@ -132,6 +152,8 @@ describe('v3.MetricServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IGetMetricDescriptorRequest = {}; request.name = ''; @@ -155,6 +177,8 @@ describe('v3.MetricServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IGetMetricDescriptorRequest = {}; request.name = ''; @@ -180,6 +204,8 @@ describe('v3.MetricServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.ICreateMetricDescriptorRequest = {}; request.name = ''; @@ -203,6 +229,8 @@ describe('v3.MetricServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.ICreateMetricDescriptorRequest = {}; request.name = ''; @@ -228,6 +256,8 @@ describe('v3.MetricServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IDeleteMetricDescriptorRequest = {}; request.name = ''; @@ -251,6 +281,8 @@ describe('v3.MetricServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IDeleteMetricDescriptorRequest = {}; request.name = ''; @@ -276,6 +308,8 @@ describe('v3.MetricServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.ICreateTimeSeriesRequest = {}; request.name = ''; @@ -299,6 +333,8 @@ describe('v3.MetricServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.ICreateTimeSeriesRequest = {}; request.name = ''; @@ -324,6 +360,8 @@ describe('v3.MetricServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest = {}; request.name = ''; @@ -347,6 +385,8 @@ describe('v3.MetricServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IListMonitoredResourceDescriptorsRequest = {}; request.name = ''; @@ -372,6 +412,8 @@ describe('v3.MetricServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IListMetricDescriptorsRequest = {}; request.name = ''; @@ -395,6 +437,8 @@ describe('v3.MetricServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IListMetricDescriptorsRequest = {}; request.name = ''; @@ -420,6 +464,8 @@ describe('v3.MetricServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IListTimeSeriesRequest = {}; request.name = ''; @@ -443,6 +489,8 @@ describe('v3.MetricServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IListTimeSeriesRequest = {}; request.name = ''; diff --git a/baselines/monitoring/test/gapic-notification_channel_service-v3.ts.baseline b/baselines/monitoring/test/gapic-notification_channel_service-v3.ts.baseline index e3fff90fc..f5928fd7d 100644 --- a/baselines/monitoring/test/gapic-notification_channel_service-v3.ts.baseline +++ b/baselines/monitoring/test/gapic-notification_channel_service-v3.ts.baseline @@ -78,12 +78,30 @@ describe('v3.NotificationChannelServiceClient', () => { }); assert(client); }); + it('has initialize method and supports deferred initialization', async () => { + const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.notificationChannelServiceStub, undefined); + await client.initialize(); + assert(client.notificationChannelServiceStub); + }); + it('has close method', () => { + const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.close(); + }); describe('getNotificationChannelDescriptor', () => { it('invokes getNotificationChannelDescriptor without error', done => { const client = new notificationchannelserviceModule.v3.NotificationChannelServiceClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IGetNotificationChannelDescriptorRequest = {}; request.name = ''; @@ -107,6 +125,8 @@ describe('v3.NotificationChannelServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IGetNotificationChannelDescriptorRequest = {}; request.name = ''; @@ -132,6 +152,8 @@ describe('v3.NotificationChannelServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IGetNotificationChannelRequest = {}; request.name = ''; @@ -155,6 +177,8 @@ describe('v3.NotificationChannelServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IGetNotificationChannelRequest = {}; request.name = ''; @@ -180,6 +204,8 @@ describe('v3.NotificationChannelServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.ICreateNotificationChannelRequest = {}; request.name = ''; @@ -203,6 +229,8 @@ describe('v3.NotificationChannelServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.ICreateNotificationChannelRequest = {}; request.name = ''; @@ -228,6 +256,8 @@ describe('v3.NotificationChannelServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IUpdateNotificationChannelRequest = {}; request.notificationChannel = {}; @@ -252,6 +282,8 @@ describe('v3.NotificationChannelServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IUpdateNotificationChannelRequest = {}; request.notificationChannel = {}; @@ -278,6 +310,8 @@ describe('v3.NotificationChannelServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IDeleteNotificationChannelRequest = {}; request.name = ''; @@ -301,6 +335,8 @@ describe('v3.NotificationChannelServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IDeleteNotificationChannelRequest = {}; request.name = ''; @@ -326,6 +362,8 @@ describe('v3.NotificationChannelServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest = {}; request.name = ''; @@ -349,6 +387,8 @@ describe('v3.NotificationChannelServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.ISendNotificationChannelVerificationCodeRequest = {}; request.name = ''; @@ -374,6 +414,8 @@ describe('v3.NotificationChannelServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest = {}; request.name = ''; @@ -397,6 +439,8 @@ describe('v3.NotificationChannelServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IGetNotificationChannelVerificationCodeRequest = {}; request.name = ''; @@ -422,6 +466,8 @@ describe('v3.NotificationChannelServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IVerifyNotificationChannelRequest = {}; request.name = ''; @@ -445,6 +491,8 @@ describe('v3.NotificationChannelServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IVerifyNotificationChannelRequest = {}; request.name = ''; @@ -470,6 +518,8 @@ describe('v3.NotificationChannelServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IListNotificationChannelDescriptorsRequest = {}; request.name = ''; @@ -493,6 +543,8 @@ describe('v3.NotificationChannelServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IListNotificationChannelDescriptorsRequest = {}; request.name = ''; @@ -518,6 +570,8 @@ describe('v3.NotificationChannelServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IListNotificationChannelsRequest = {}; request.name = ''; @@ -541,6 +595,8 @@ describe('v3.NotificationChannelServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IListNotificationChannelsRequest = {}; request.name = ''; diff --git a/baselines/monitoring/test/gapic-service_monitoring_service-v3.ts.baseline b/baselines/monitoring/test/gapic-service_monitoring_service-v3.ts.baseline index 780f79dd4..9392ce2d1 100644 --- a/baselines/monitoring/test/gapic-service_monitoring_service-v3.ts.baseline +++ b/baselines/monitoring/test/gapic-service_monitoring_service-v3.ts.baseline @@ -78,12 +78,30 @@ describe('v3.ServiceMonitoringServiceClient', () => { }); assert(client); }); + it('has initialize method and supports deferred initialization', async () => { + const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.serviceMonitoringServiceStub, undefined); + await client.initialize(); + assert(client.serviceMonitoringServiceStub); + }); + it('has close method', () => { + const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.close(); + }); describe('createService', () => { it('invokes createService without error', done => { const client = new servicemonitoringserviceModule.v3.ServiceMonitoringServiceClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.ICreateServiceRequest = {}; request.parent = ''; @@ -107,6 +125,8 @@ describe('v3.ServiceMonitoringServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.ICreateServiceRequest = {}; request.parent = ''; @@ -132,6 +152,8 @@ describe('v3.ServiceMonitoringServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IGetServiceRequest = {}; request.name = ''; @@ -155,6 +177,8 @@ describe('v3.ServiceMonitoringServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IGetServiceRequest = {}; request.name = ''; @@ -180,6 +204,8 @@ describe('v3.ServiceMonitoringServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IUpdateServiceRequest = {}; request.service = {}; @@ -204,6 +230,8 @@ describe('v3.ServiceMonitoringServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IUpdateServiceRequest = {}; request.service = {}; @@ -230,6 +258,8 @@ describe('v3.ServiceMonitoringServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IDeleteServiceRequest = {}; request.name = ''; @@ -253,6 +283,8 @@ describe('v3.ServiceMonitoringServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IDeleteServiceRequest = {}; request.name = ''; @@ -278,6 +310,8 @@ describe('v3.ServiceMonitoringServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.ICreateServiceLevelObjectiveRequest = {}; request.parent = ''; @@ -301,6 +335,8 @@ describe('v3.ServiceMonitoringServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.ICreateServiceLevelObjectiveRequest = {}; request.parent = ''; @@ -326,6 +362,8 @@ describe('v3.ServiceMonitoringServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IGetServiceLevelObjectiveRequest = {}; request.name = ''; @@ -349,6 +387,8 @@ describe('v3.ServiceMonitoringServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IGetServiceLevelObjectiveRequest = {}; request.name = ''; @@ -374,6 +414,8 @@ describe('v3.ServiceMonitoringServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest = {}; request.serviceLevelObjective = {}; @@ -398,6 +440,8 @@ describe('v3.ServiceMonitoringServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IUpdateServiceLevelObjectiveRequest = {}; request.serviceLevelObjective = {}; @@ -424,6 +468,8 @@ describe('v3.ServiceMonitoringServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest = {}; request.name = ''; @@ -447,6 +493,8 @@ describe('v3.ServiceMonitoringServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IDeleteServiceLevelObjectiveRequest = {}; request.name = ''; @@ -472,6 +520,8 @@ describe('v3.ServiceMonitoringServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IListServicesRequest = {}; request.parent = ''; @@ -495,6 +545,8 @@ describe('v3.ServiceMonitoringServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IListServicesRequest = {}; request.parent = ''; @@ -520,6 +572,8 @@ describe('v3.ServiceMonitoringServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IListServiceLevelObjectivesRequest = {}; request.parent = ''; @@ -543,6 +597,8 @@ describe('v3.ServiceMonitoringServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IListServiceLevelObjectivesRequest = {}; request.parent = ''; diff --git a/baselines/monitoring/test/gapic-uptime_check_service-v3.ts.baseline b/baselines/monitoring/test/gapic-uptime_check_service-v3.ts.baseline index f7c232f70..21a9700c3 100644 --- a/baselines/monitoring/test/gapic-uptime_check_service-v3.ts.baseline +++ b/baselines/monitoring/test/gapic-uptime_check_service-v3.ts.baseline @@ -78,12 +78,30 @@ describe('v3.UptimeCheckServiceClient', () => { }); assert(client); }); + it('has initialize method and supports deferred initialization', async () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.uptimeCheckServiceStub, undefined); + await client.initialize(); + assert(client.uptimeCheckServiceStub); + }); + it('has close method', () => { + const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.close(); + }); describe('getUptimeCheckConfig', () => { it('invokes getUptimeCheckConfig without error', done => { const client = new uptimecheckserviceModule.v3.UptimeCheckServiceClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IGetUptimeCheckConfigRequest = {}; request.name = ''; @@ -107,6 +125,8 @@ describe('v3.UptimeCheckServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IGetUptimeCheckConfigRequest = {}; request.name = ''; @@ -132,6 +152,8 @@ describe('v3.UptimeCheckServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.ICreateUptimeCheckConfigRequest = {}; request.parent = ''; @@ -155,6 +177,8 @@ describe('v3.UptimeCheckServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.ICreateUptimeCheckConfigRequest = {}; request.parent = ''; @@ -180,6 +204,8 @@ describe('v3.UptimeCheckServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IUpdateUptimeCheckConfigRequest = {}; request.uptimeCheckConfig = {}; @@ -204,6 +230,8 @@ describe('v3.UptimeCheckServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IUpdateUptimeCheckConfigRequest = {}; request.uptimeCheckConfig = {}; @@ -230,6 +258,8 @@ describe('v3.UptimeCheckServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IDeleteUptimeCheckConfigRequest = {}; request.name = ''; @@ -253,6 +283,8 @@ describe('v3.UptimeCheckServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IDeleteUptimeCheckConfigRequest = {}; request.name = ''; @@ -278,6 +310,8 @@ describe('v3.UptimeCheckServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IListUptimeCheckConfigsRequest = {}; request.parent = ''; @@ -301,6 +335,8 @@ describe('v3.UptimeCheckServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IListUptimeCheckConfigsRequest = {}; request.parent = ''; @@ -326,6 +362,8 @@ describe('v3.UptimeCheckServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IListUptimeCheckIpsRequest = {}; // Mock response @@ -348,6 +386,8 @@ describe('v3.UptimeCheckServiceClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.monitoring.v3.IListUptimeCheckIpsRequest = {}; // Mock response diff --git a/baselines/redis/src/v1beta1/cloud_redis_client.ts.baseline b/baselines/redis/src/v1beta1/cloud_redis_client.ts.baseline index ababe81cf..953aba00a 100644 --- a/baselines/redis/src/v1beta1/cloud_redis_client.ts.baseline +++ b/baselines/redis/src/v1beta1/cloud_redis_client.ts.baseline @@ -50,9 +50,14 @@ export class CloudRedisClient { private _innerApiCalls: {[name: string]: Function}; private _pathTemplates: {[name: string]: gax.PathTemplate}; private _terminated = false; + private _opts: ClientOptions; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; auth: gax.GoogleAuth; operationsClient: gax.OperationsClient; - cloudRedisStub: Promise<{[name: string]: Function}>; + cloudRedisStub?: Promise<{[name: string]: Function}>; /** * Construct an instance of CloudRedisClient. @@ -105,28 +110,31 @@ export class CloudRedisClient { // If we are in browser, we are already using fallback because of the // "browser" field in package.json. // But if we were explicitly requested to use fallback, let's do it now. - const gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; + this._gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; // Create a `gaxGrpc` object, with any grpc-specific options // sent to the client. opts.scopes = (this.constructor as typeof CloudRedisClient).scopes; - const gaxGrpc = new gaxModule.GrpcClient(opts); + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (gaxGrpc.auth as gax.GoogleAuth); + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); // Determine the client header string. const clientHeader = [ - `gax/${gaxModule.version}`, + `gax/${this._gaxModule.version}`, `gapic/${version}`, ]; if (typeof process !== 'undefined' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { - clientHeader.push(`gl-web/${gaxModule.version}`); + clientHeader.push(`gl-web/${this._gaxModule.version}`); } if (!opts.fallback) { - clientHeader.push(`grpc/${gaxGrpc.grpcVersion}`); + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { clientHeader.push(`${opts.libName}/${opts.libVersion}`); @@ -136,7 +144,7 @@ export class CloudRedisClient { // For browsers, pass the JSON content. const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); - const protos = gaxGrpc.loadProto( + this._protos = this._gaxGrpc.loadProto( opts.fallback ? require("../../protos/protos.json") : nodejsProtoPath @@ -146,10 +154,10 @@ export class CloudRedisClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this._pathTemplates = { - instancePathTemplate: new gaxModule.PathTemplate( + instancePathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/locations/{location}/instances/{instance}' ), - locationPathTemplate: new gaxModule.PathTemplate( + locationPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/locations/{location}' ), }; @@ -159,19 +167,19 @@ export class CloudRedisClient { // pages). Denote the keys used for pagination and results. this._descriptors.page = { listInstances: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'instances') + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'instances') }; // This API contains "long-running operations", which return a // an Operation object that allows for tracking of the operation, // rather than holding a request open. const protoFilesRoot = opts.fallback? - gaxModule.protobuf.Root.fromJSON(require("../../protos/protos.json")) : - gaxModule.protobuf.loadSync(nodejsProtoPath); + this._gaxModule.protobuf.Root.fromJSON(require("../../protos/protos.json")) : + this._gaxModule.protobuf.loadSync(nodejsProtoPath); - this.operationsClient = gaxModule.lro({ + this.operationsClient = this._gaxModule.lro({ auth: this.auth, - grpc: 'grpc' in gaxGrpc ? gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined }).operationsClient(opts); const createInstanceResponse = protoFilesRoot.lookup( '.google.cloud.redis.v1beta1.Instance') as gax.protobuf.Type; @@ -199,34 +207,34 @@ export class CloudRedisClient { '.google.protobuf.Any') as gax.protobuf.Type; this._descriptors.longrunning = { - createInstance: new gaxModule.LongrunningDescriptor( + createInstance: new this._gaxModule.LongrunningDescriptor( this.operationsClient, createInstanceResponse.decode.bind(createInstanceResponse), createInstanceMetadata.decode.bind(createInstanceMetadata)), - updateInstance: new gaxModule.LongrunningDescriptor( + updateInstance: new this._gaxModule.LongrunningDescriptor( this.operationsClient, updateInstanceResponse.decode.bind(updateInstanceResponse), updateInstanceMetadata.decode.bind(updateInstanceMetadata)), - importInstance: new gaxModule.LongrunningDescriptor( + importInstance: new this._gaxModule.LongrunningDescriptor( this.operationsClient, importInstanceResponse.decode.bind(importInstanceResponse), importInstanceMetadata.decode.bind(importInstanceMetadata)), - exportInstance: new gaxModule.LongrunningDescriptor( + exportInstance: new this._gaxModule.LongrunningDescriptor( this.operationsClient, exportInstanceResponse.decode.bind(exportInstanceResponse), exportInstanceMetadata.decode.bind(exportInstanceMetadata)), - failoverInstance: new gaxModule.LongrunningDescriptor( + failoverInstance: new this._gaxModule.LongrunningDescriptor( this.operationsClient, failoverInstanceResponse.decode.bind(failoverInstanceResponse), failoverInstanceMetadata.decode.bind(failoverInstanceMetadata)), - deleteInstance: new gaxModule.LongrunningDescriptor( + deleteInstance: new this._gaxModule.LongrunningDescriptor( this.operationsClient, deleteInstanceResponse.decode.bind(deleteInstanceResponse), deleteInstanceMetadata.decode.bind(deleteInstanceMetadata)) }; // Put together the default options sent with requests. - const defaults = gaxGrpc.constructSettings( + this._defaults = this._gaxGrpc.constructSettings( 'google.cloud.redis.v1beta1.CloudRedis', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); @@ -234,15 +242,33 @@ export class CloudRedisClient { // of calling the API is handled in `google-gax`, with this code // merely providing the destination and request information. this._innerApiCalls = {}; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.cloudRedisStub) { + return this.cloudRedisStub; + } // Put together the "service stub" for // google.cloud.redis.v1beta1.CloudRedis. - this.cloudRedisStub = gaxGrpc.createStub( - opts.fallback ? - (protos as protobuf.Root).lookupService('google.cloud.redis.v1beta1.CloudRedis') : + this.cloudRedisStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.cloud.redis.v1beta1.CloudRedis') : // tslint:disable-next-line no-any - (protos as any).google.cloud.redis.v1beta1.CloudRedis, - opts) as Promise<{[method: string]: Function}>; + (this._protos as any).google.cloud.redis.v1beta1.CloudRedis, + this._opts) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -261,9 +287,9 @@ export class CloudRedisClient { throw err; }); - const apiCall = gaxModule.createApiCall( + const apiCall = this._gaxModule.createApiCall( innerCallPromise, - defaults[methodName], + this._defaults[methodName], this._descriptors.page[methodName] || this._descriptors.stream[methodName] || this._descriptors.longrunning[methodName] @@ -277,6 +303,8 @@ export class CloudRedisClient { return apiCall(argument, callOptions, callback); }; } + + return this.cloudRedisStub; } /** @@ -389,6 +417,7 @@ export class CloudRedisClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.getInstance(request, options, callback); } @@ -473,6 +502,7 @@ export class CloudRedisClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.createInstance(request, options, callback); } updateInstance( @@ -546,6 +576,7 @@ export class CloudRedisClient { ] = gax.routingHeader.fromParams({ 'instance.name': request.instance!.name || '', }); + this.initialize(); return this._innerApiCalls.updateInstance(request, options, callback); } importInstance( @@ -616,6 +647,7 @@ export class CloudRedisClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.importInstance(request, options, callback); } exportInstance( @@ -684,6 +716,7 @@ export class CloudRedisClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.exportInstance(request, options, callback); } failoverInstance( @@ -749,6 +782,7 @@ export class CloudRedisClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.failoverInstance(request, options, callback); } deleteInstance( @@ -811,6 +845,7 @@ export class CloudRedisClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.deleteInstance(request, options, callback); } listInstances( @@ -905,6 +940,7 @@ export class CloudRedisClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.listInstances(request, options, callback); } @@ -957,6 +993,7 @@ export class CloudRedisClient { 'parent': request.parent || '', }); const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listInstances.createStream( this._innerApiCalls.listInstances as gax.GaxCall, request, @@ -1058,8 +1095,9 @@ export class CloudRedisClient { * The client will no longer be usable and all future behavior is undefined. */ close(): Promise { + this.initialize(); if (!this._terminated) { - return this.cloudRedisStub.then(stub => { + return this.cloudRedisStub!.then(stub => { this._terminated = true; stub.close(); }); diff --git a/baselines/redis/test/gapic-cloud_redis-v1beta1.ts.baseline b/baselines/redis/test/gapic-cloud_redis-v1beta1.ts.baseline index 95ae5616d..acfe49320 100644 --- a/baselines/redis/test/gapic-cloud_redis-v1beta1.ts.baseline +++ b/baselines/redis/test/gapic-cloud_redis-v1beta1.ts.baseline @@ -96,12 +96,30 @@ describe('v1beta1.CloudRedisClient', () => { }); assert(client); }); + it('has initialize method and supports deferred initialization', async () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.cloudRedisStub, undefined); + await client.initialize(); + assert(client.cloudRedisStub); + }); + it('has close method', () => { + const client = new cloudredisModule.v1beta1.CloudRedisClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.close(); + }); describe('getInstance', () => { it('invokes getInstance without error', done => { const client = new cloudredisModule.v1beta1.CloudRedisClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.redis.v1beta1.IGetInstanceRequest = {}; request.name = ''; @@ -125,6 +143,8 @@ describe('v1beta1.CloudRedisClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.redis.v1beta1.IGetInstanceRequest = {}; request.name = ''; @@ -150,6 +170,8 @@ describe('v1beta1.CloudRedisClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.redis.v1beta1.ICreateInstanceRequest = {}; request.parent = ''; @@ -176,6 +198,8 @@ describe('v1beta1.CloudRedisClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.redis.v1beta1.ICreateInstanceRequest = {}; request.parent = ''; @@ -205,6 +229,8 @@ describe('v1beta1.CloudRedisClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.redis.v1beta1.IUpdateInstanceRequest = {}; request.instance = {}; @@ -232,6 +258,8 @@ describe('v1beta1.CloudRedisClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.redis.v1beta1.IUpdateInstanceRequest = {}; request.instance = {}; @@ -262,6 +290,8 @@ describe('v1beta1.CloudRedisClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.redis.v1beta1.IImportInstanceRequest = {}; request.name = ''; @@ -288,6 +318,8 @@ describe('v1beta1.CloudRedisClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.redis.v1beta1.IImportInstanceRequest = {}; request.name = ''; @@ -317,6 +349,8 @@ describe('v1beta1.CloudRedisClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.redis.v1beta1.IExportInstanceRequest = {}; request.name = ''; @@ -343,6 +377,8 @@ describe('v1beta1.CloudRedisClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.redis.v1beta1.IExportInstanceRequest = {}; request.name = ''; @@ -372,6 +408,8 @@ describe('v1beta1.CloudRedisClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.redis.v1beta1.IFailoverInstanceRequest = {}; request.name = ''; @@ -398,6 +436,8 @@ describe('v1beta1.CloudRedisClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.redis.v1beta1.IFailoverInstanceRequest = {}; request.name = ''; @@ -427,6 +467,8 @@ describe('v1beta1.CloudRedisClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.redis.v1beta1.IDeleteInstanceRequest = {}; request.name = ''; @@ -453,6 +495,8 @@ describe('v1beta1.CloudRedisClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.redis.v1beta1.IDeleteInstanceRequest = {}; request.name = ''; @@ -482,6 +526,8 @@ describe('v1beta1.CloudRedisClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.redis.v1beta1.IListInstancesRequest = {}; request.parent = ''; @@ -505,6 +551,8 @@ describe('v1beta1.CloudRedisClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.redis.v1beta1.IListInstancesRequest = {}; request.parent = ''; diff --git a/baselines/showcase/src/v1beta1/echo_client.ts.baseline b/baselines/showcase/src/v1beta1/echo_client.ts.baseline index ce19047e5..2f2a88f5b 100644 --- a/baselines/showcase/src/v1beta1/echo_client.ts.baseline +++ b/baselines/showcase/src/v1beta1/echo_client.ts.baseline @@ -40,9 +40,14 @@ export class EchoClient { private _innerApiCalls: {[name: string]: Function}; private _pathTemplates: {[name: string]: gax.PathTemplate}; private _terminated = false; + private _opts: ClientOptions; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; auth: gax.GoogleAuth; operationsClient: gax.OperationsClient; - echoStub: Promise<{[name: string]: Function}>; + echoStub?: Promise<{[name: string]: Function}>; /** * Construct an instance of EchoClient. @@ -95,28 +100,31 @@ export class EchoClient { // If we are in browser, we are already using fallback because of the // "browser" field in package.json. // But if we were explicitly requested to use fallback, let's do it now. - const gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; + this._gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; // Create a `gaxGrpc` object, with any grpc-specific options // sent to the client. opts.scopes = (this.constructor as typeof EchoClient).scopes; - const gaxGrpc = new gaxModule.GrpcClient(opts); + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (gaxGrpc.auth as gax.GoogleAuth); + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); // Determine the client header string. const clientHeader = [ - `gax/${gaxModule.version}`, + `gax/${this._gaxModule.version}`, `gapic/${version}`, ]; if (typeof process !== 'undefined' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { - clientHeader.push(`gl-web/${gaxModule.version}`); + clientHeader.push(`gl-web/${this._gaxModule.version}`); } if (!opts.fallback) { - clientHeader.push(`grpc/${gaxGrpc.grpcVersion}`); + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { clientHeader.push(`${opts.libName}/${opts.libVersion}`); @@ -126,7 +134,7 @@ export class EchoClient { // For browsers, pass the JSON content. const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); - const protos = gaxGrpc.loadProto( + this._protos = this._gaxGrpc.loadProto( opts.fallback ? require("../../protos/protos.json") : nodejsProtoPath @@ -136,25 +144,25 @@ export class EchoClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this._pathTemplates = { - blueprintPathTemplate: new gaxModule.PathTemplate( + blueprintPathTemplate: new this._gaxModule.PathTemplate( 'sessions/{session}/tests/{test}/blueprints/{blueprint}' ), - roomPathTemplate: new gaxModule.PathTemplate( + roomPathTemplate: new this._gaxModule.PathTemplate( 'rooms/{room_id}' ), - roomIdBlurbIdPathTemplate: new gaxModule.PathTemplate( + roomIdBlurbIdPathTemplate: new this._gaxModule.PathTemplate( 'rooms/{room_id}/blurbs/{blurb_id}' ), - sessionPathTemplate: new gaxModule.PathTemplate( + sessionPathTemplate: new this._gaxModule.PathTemplate( 'sessions/{session}' ), - testPathTemplate: new gaxModule.PathTemplate( + testPathTemplate: new this._gaxModule.PathTemplate( 'sessions/{session}/tests/{test}' ), - userPathTemplate: new gaxModule.PathTemplate( + userPathTemplate: new this._gaxModule.PathTemplate( 'users/{user_id}' ), - userIdBlurbIdPathTemplate: new gaxModule.PathTemplate( + userIdBlurbIdPathTemplate: new this._gaxModule.PathTemplate( 'user/{user_id}/profile/blurbs/{blurb_id}' ), }; @@ -164,27 +172,27 @@ export class EchoClient { // pages). Denote the keys used for pagination and results. this._descriptors.page = { pagedExpand: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'responses') + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'responses') }; // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this._descriptors.stream = { - expand: new gaxModule.StreamDescriptor(gax.StreamType.SERVER_STREAMING), - collect: new gaxModule.StreamDescriptor(gax.StreamType.CLIENT_STREAMING), - chat: new gaxModule.StreamDescriptor(gax.StreamType.BIDI_STREAMING) + expand: new this._gaxModule.StreamDescriptor(gax.StreamType.SERVER_STREAMING), + collect: new this._gaxModule.StreamDescriptor(gax.StreamType.CLIENT_STREAMING), + chat: new this._gaxModule.StreamDescriptor(gax.StreamType.BIDI_STREAMING) }; // This API contains "long-running operations", which return a // an Operation object that allows for tracking of the operation, // rather than holding a request open. const protoFilesRoot = opts.fallback? - gaxModule.protobuf.Root.fromJSON(require("../../protos/protos.json")) : - gaxModule.protobuf.loadSync(nodejsProtoPath); + this._gaxModule.protobuf.Root.fromJSON(require("../../protos/protos.json")) : + this._gaxModule.protobuf.loadSync(nodejsProtoPath); - this.operationsClient = gaxModule.lro({ + this.operationsClient = this._gaxModule.lro({ auth: this.auth, - grpc: 'grpc' in gaxGrpc ? gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined }).operationsClient(opts); const waitResponse = protoFilesRoot.lookup( '.google.showcase.v1beta1.WaitResponse') as gax.protobuf.Type; @@ -192,14 +200,14 @@ export class EchoClient { '.google.showcase.v1beta1.WaitMetadata') as gax.protobuf.Type; this._descriptors.longrunning = { - wait: new gaxModule.LongrunningDescriptor( + wait: new this._gaxModule.LongrunningDescriptor( this.operationsClient, waitResponse.decode.bind(waitResponse), waitMetadata.decode.bind(waitMetadata)) }; // Put together the default options sent with requests. - const defaults = gaxGrpc.constructSettings( + this._defaults = this._gaxGrpc.constructSettings( 'google.showcase.v1beta1.Echo', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); @@ -207,15 +215,33 @@ export class EchoClient { // of calling the API is handled in `google-gax`, with this code // merely providing the destination and request information. this._innerApiCalls = {}; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.echoStub) { + return this.echoStub; + } // Put together the "service stub" for // google.showcase.v1beta1.Echo. - this.echoStub = gaxGrpc.createStub( - opts.fallback ? - (protos as protobuf.Root).lookupService('google.showcase.v1beta1.Echo') : + this.echoStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.Echo') : // tslint:disable-next-line no-any - (protos as any).google.showcase.v1beta1.Echo, - opts) as Promise<{[method: string]: Function}>; + (this._protos as any).google.showcase.v1beta1.Echo, + this._opts) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -234,9 +260,9 @@ export class EchoClient { throw err; }); - const apiCall = gaxModule.createApiCall( + const apiCall = this._gaxModule.createApiCall( innerCallPromise, - defaults[methodName], + this._defaults[methodName], this._descriptors.page[methodName] || this._descriptors.stream[methodName] || this._descriptors.longrunning[methodName] @@ -250,6 +276,8 @@ export class EchoClient { return apiCall(argument, callOptions, callback); }; } + + return this.echoStub; } /** @@ -351,6 +379,7 @@ export class EchoClient { options = optionsOrCallback as gax.CallOptions; } options = options || {}; + this.initialize(); return this._innerApiCalls.echo(request, options, callback); } block( @@ -410,6 +439,7 @@ export class EchoClient { options = optionsOrCallback as gax.CallOptions; } options = options || {}; + this.initialize(); return this._innerApiCalls.block(request, options, callback); } @@ -434,6 +464,7 @@ export class EchoClient { gax.CancellableStream{ request = request || {}; options = options || {}; + this.initialize(); return this._innerApiCalls.expand(request, options); } @@ -471,6 +502,7 @@ export class EchoClient { optionsOrCallback = {}; } const options = optionsOrCallback as gax.CallOptions; + this.initialize(); return this._innerApiCalls.collect(null, options, callback); } @@ -488,7 +520,8 @@ export class EchoClient { */ chat( options?: gax.CallOptions): - gax.CancellableStream{ + gax.CancellableStream { + this.initialize(); return this._innerApiCalls.chat(options); } @@ -550,6 +583,7 @@ export class EchoClient { options = optionsOrCallback as gax.CallOptions; } options = options || {}; + this.initialize(); return this._innerApiCalls.wait(request, options, callback); } pagedExpand( @@ -622,6 +656,7 @@ export class EchoClient { options = optionsOrCallback as gax.CallOptions; } options = options || {}; + this.initialize(); return this._innerApiCalls.pagedExpand(request, options, callback); } @@ -658,6 +693,7 @@ export class EchoClient { request = request || {}; options = options || {}; const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.pagedExpand.createStream( this._innerApiCalls.pagedExpand as gax.GaxCall, request, @@ -900,8 +936,9 @@ export class EchoClient { * The client will no longer be usable and all future behavior is undefined. */ close(): Promise { + this.initialize(); if (!this._terminated) { - return this.echoStub.then(stub => { + return this.echoStub!.then(stub => { this._terminated = true; stub.close(); }); diff --git a/baselines/showcase/src/v1beta1/identity_client.ts.baseline b/baselines/showcase/src/v1beta1/identity_client.ts.baseline index b716d4d42..24005f2c0 100644 --- a/baselines/showcase/src/v1beta1/identity_client.ts.baseline +++ b/baselines/showcase/src/v1beta1/identity_client.ts.baseline @@ -36,8 +36,13 @@ export class IdentityClient { private _innerApiCalls: {[name: string]: Function}; private _pathTemplates: {[name: string]: gax.PathTemplate}; private _terminated = false; + private _opts: ClientOptions; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; auth: gax.GoogleAuth; - identityStub: Promise<{[name: string]: Function}>; + identityStub?: Promise<{[name: string]: Function}>; /** * Construct an instance of IdentityClient. @@ -90,28 +95,31 @@ export class IdentityClient { // If we are in browser, we are already using fallback because of the // "browser" field in package.json. // But if we were explicitly requested to use fallback, let's do it now. - const gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; + this._gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; // Create a `gaxGrpc` object, with any grpc-specific options // sent to the client. opts.scopes = (this.constructor as typeof IdentityClient).scopes; - const gaxGrpc = new gaxModule.GrpcClient(opts); + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (gaxGrpc.auth as gax.GoogleAuth); + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); // Determine the client header string. const clientHeader = [ - `gax/${gaxModule.version}`, + `gax/${this._gaxModule.version}`, `gapic/${version}`, ]; if (typeof process !== 'undefined' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { - clientHeader.push(`gl-web/${gaxModule.version}`); + clientHeader.push(`gl-web/${this._gaxModule.version}`); } if (!opts.fallback) { - clientHeader.push(`grpc/${gaxGrpc.grpcVersion}`); + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { clientHeader.push(`${opts.libName}/${opts.libVersion}`); @@ -121,7 +129,7 @@ export class IdentityClient { // For browsers, pass the JSON content. const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); - const protos = gaxGrpc.loadProto( + this._protos = this._gaxGrpc.loadProto( opts.fallback ? require("../../protos/protos.json") : nodejsProtoPath @@ -131,25 +139,25 @@ export class IdentityClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this._pathTemplates = { - blueprintPathTemplate: new gaxModule.PathTemplate( + blueprintPathTemplate: new this._gaxModule.PathTemplate( 'sessions/{session}/tests/{test}/blueprints/{blueprint}' ), - roomPathTemplate: new gaxModule.PathTemplate( + roomPathTemplate: new this._gaxModule.PathTemplate( 'rooms/{room_id}' ), - roomIdBlurbIdPathTemplate: new gaxModule.PathTemplate( + roomIdBlurbIdPathTemplate: new this._gaxModule.PathTemplate( 'rooms/{room_id}/blurbs/{blurb_id}' ), - sessionPathTemplate: new gaxModule.PathTemplate( + sessionPathTemplate: new this._gaxModule.PathTemplate( 'sessions/{session}' ), - testPathTemplate: new gaxModule.PathTemplate( + testPathTemplate: new this._gaxModule.PathTemplate( 'sessions/{session}/tests/{test}' ), - userPathTemplate: new gaxModule.PathTemplate( + userPathTemplate: new this._gaxModule.PathTemplate( 'users/{user_id}' ), - userIdBlurbIdPathTemplate: new gaxModule.PathTemplate( + userIdBlurbIdPathTemplate: new this._gaxModule.PathTemplate( 'user/{user_id}/profile/blurbs/{blurb_id}' ), }; @@ -159,11 +167,11 @@ export class IdentityClient { // pages). Denote the keys used for pagination and results. this._descriptors.page = { listUsers: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'users') + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'users') }; // Put together the default options sent with requests. - const defaults = gaxGrpc.constructSettings( + this._defaults = this._gaxGrpc.constructSettings( 'google.showcase.v1beta1.Identity', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); @@ -171,15 +179,33 @@ export class IdentityClient { // of calling the API is handled in `google-gax`, with this code // merely providing the destination and request information. this._innerApiCalls = {}; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.identityStub) { + return this.identityStub; + } // Put together the "service stub" for // google.showcase.v1beta1.Identity. - this.identityStub = gaxGrpc.createStub( - opts.fallback ? - (protos as protobuf.Root).lookupService('google.showcase.v1beta1.Identity') : + this.identityStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.Identity') : // tslint:disable-next-line no-any - (protos as any).google.showcase.v1beta1.Identity, - opts) as Promise<{[method: string]: Function}>; + (this._protos as any).google.showcase.v1beta1.Identity, + this._opts) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -198,9 +224,9 @@ export class IdentityClient { throw err; }); - const apiCall = gaxModule.createApiCall( + const apiCall = this._gaxModule.createApiCall( innerCallPromise, - defaults[methodName], + this._defaults[methodName], this._descriptors.page[methodName] || this._descriptors.stream[methodName] || this._descriptors.longrunning[methodName] @@ -214,6 +240,8 @@ export class IdentityClient { return apiCall(argument, callOptions, callback); }; } + + return this.identityStub; } /** @@ -315,6 +343,7 @@ export class IdentityClient { options = optionsOrCallback as gax.CallOptions; } options = options || {}; + this.initialize(); return this._innerApiCalls.createUser(request, options, callback); } getUser( @@ -374,6 +403,7 @@ export class IdentityClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.getUser(request, options, callback); } updateUser( @@ -436,6 +466,7 @@ export class IdentityClient { ] = gax.routingHeader.fromParams({ 'user.name': request.user!.name || '', }); + this.initialize(); return this._innerApiCalls.updateUser(request, options, callback); } deleteUser( @@ -495,6 +526,7 @@ export class IdentityClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.deleteUser(request, options, callback); } @@ -568,6 +600,7 @@ export class IdentityClient { options = optionsOrCallback as gax.CallOptions; } options = options || {}; + this.initialize(); return this._innerApiCalls.listUsers(request, options, callback); } @@ -605,6 +638,7 @@ export class IdentityClient { request = request || {}; options = options || {}; const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listUsers.createStream( this._innerApiCalls.listUsers as gax.GaxCall, request, @@ -847,8 +881,9 @@ export class IdentityClient { * The client will no longer be usable and all future behavior is undefined. */ close(): Promise { + this.initialize(); if (!this._terminated) { - return this.identityStub.then(stub => { + return this.identityStub!.then(stub => { this._terminated = true; stub.close(); }); diff --git a/baselines/showcase/src/v1beta1/messaging_client.ts.baseline b/baselines/showcase/src/v1beta1/messaging_client.ts.baseline index a1652aedc..204080ee7 100644 --- a/baselines/showcase/src/v1beta1/messaging_client.ts.baseline +++ b/baselines/showcase/src/v1beta1/messaging_client.ts.baseline @@ -39,9 +39,14 @@ export class MessagingClient { private _innerApiCalls: {[name: string]: Function}; private _pathTemplates: {[name: string]: gax.PathTemplate}; private _terminated = false; + private _opts: ClientOptions; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; auth: gax.GoogleAuth; operationsClient: gax.OperationsClient; - messagingStub: Promise<{[name: string]: Function}>; + messagingStub?: Promise<{[name: string]: Function}>; /** * Construct an instance of MessagingClient. @@ -94,28 +99,31 @@ export class MessagingClient { // If we are in browser, we are already using fallback because of the // "browser" field in package.json. // But if we were explicitly requested to use fallback, let's do it now. - const gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; + this._gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; // Create a `gaxGrpc` object, with any grpc-specific options // sent to the client. opts.scopes = (this.constructor as typeof MessagingClient).scopes; - const gaxGrpc = new gaxModule.GrpcClient(opts); + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (gaxGrpc.auth as gax.GoogleAuth); + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); // Determine the client header string. const clientHeader = [ - `gax/${gaxModule.version}`, + `gax/${this._gaxModule.version}`, `gapic/${version}`, ]; if (typeof process !== 'undefined' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { - clientHeader.push(`gl-web/${gaxModule.version}`); + clientHeader.push(`gl-web/${this._gaxModule.version}`); } if (!opts.fallback) { - clientHeader.push(`grpc/${gaxGrpc.grpcVersion}`); + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { clientHeader.push(`${opts.libName}/${opts.libVersion}`); @@ -125,7 +133,7 @@ export class MessagingClient { // For browsers, pass the JSON content. const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); - const protos = gaxGrpc.loadProto( + this._protos = this._gaxGrpc.loadProto( opts.fallback ? require("../../protos/protos.json") : nodejsProtoPath @@ -135,25 +143,25 @@ export class MessagingClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this._pathTemplates = { - blueprintPathTemplate: new gaxModule.PathTemplate( + blueprintPathTemplate: new this._gaxModule.PathTemplate( 'sessions/{session}/tests/{test}/blueprints/{blueprint}' ), - roomPathTemplate: new gaxModule.PathTemplate( + roomPathTemplate: new this._gaxModule.PathTemplate( 'rooms/{room_id}' ), - roomIdBlurbIdPathTemplate: new gaxModule.PathTemplate( + roomIdBlurbIdPathTemplate: new this._gaxModule.PathTemplate( 'rooms/{room_id}/blurbs/{blurb_id}' ), - sessionPathTemplate: new gaxModule.PathTemplate( + sessionPathTemplate: new this._gaxModule.PathTemplate( 'sessions/{session}' ), - testPathTemplate: new gaxModule.PathTemplate( + testPathTemplate: new this._gaxModule.PathTemplate( 'sessions/{session}/tests/{test}' ), - userPathTemplate: new gaxModule.PathTemplate( + userPathTemplate: new this._gaxModule.PathTemplate( 'users/{user_id}' ), - userIdBlurbIdPathTemplate: new gaxModule.PathTemplate( + userIdBlurbIdPathTemplate: new this._gaxModule.PathTemplate( 'user/{user_id}/profile/blurbs/{blurb_id}' ), }; @@ -163,29 +171,29 @@ export class MessagingClient { // pages). Denote the keys used for pagination and results. this._descriptors.page = { listRooms: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'rooms'), + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'rooms'), listBlurbs: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'blurbs') + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'blurbs') }; // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this._descriptors.stream = { - streamBlurbs: new gaxModule.StreamDescriptor(gax.StreamType.SERVER_STREAMING), - sendBlurbs: new gaxModule.StreamDescriptor(gax.StreamType.CLIENT_STREAMING), - connect: new gaxModule.StreamDescriptor(gax.StreamType.BIDI_STREAMING) + streamBlurbs: new this._gaxModule.StreamDescriptor(gax.StreamType.SERVER_STREAMING), + sendBlurbs: new this._gaxModule.StreamDescriptor(gax.StreamType.CLIENT_STREAMING), + connect: new this._gaxModule.StreamDescriptor(gax.StreamType.BIDI_STREAMING) }; // This API contains "long-running operations", which return a // an Operation object that allows for tracking of the operation, // rather than holding a request open. const protoFilesRoot = opts.fallback? - gaxModule.protobuf.Root.fromJSON(require("../../protos/protos.json")) : - gaxModule.protobuf.loadSync(nodejsProtoPath); + this._gaxModule.protobuf.Root.fromJSON(require("../../protos/protos.json")) : + this._gaxModule.protobuf.loadSync(nodejsProtoPath); - this.operationsClient = gaxModule.lro({ + this.operationsClient = this._gaxModule.lro({ auth: this.auth, - grpc: 'grpc' in gaxGrpc ? gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined }).operationsClient(opts); const searchBlurbsResponse = protoFilesRoot.lookup( '.google.showcase.v1beta1.SearchBlurbsResponse') as gax.protobuf.Type; @@ -193,14 +201,14 @@ export class MessagingClient { '.google.showcase.v1beta1.SearchBlurbsMetadata') as gax.protobuf.Type; this._descriptors.longrunning = { - searchBlurbs: new gaxModule.LongrunningDescriptor( + searchBlurbs: new this._gaxModule.LongrunningDescriptor( this.operationsClient, searchBlurbsResponse.decode.bind(searchBlurbsResponse), searchBlurbsMetadata.decode.bind(searchBlurbsMetadata)) }; // Put together the default options sent with requests. - const defaults = gaxGrpc.constructSettings( + this._defaults = this._gaxGrpc.constructSettings( 'google.showcase.v1beta1.Messaging', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); @@ -208,15 +216,33 @@ export class MessagingClient { // of calling the API is handled in `google-gax`, with this code // merely providing the destination and request information. this._innerApiCalls = {}; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.messagingStub) { + return this.messagingStub; + } // Put together the "service stub" for // google.showcase.v1beta1.Messaging. - this.messagingStub = gaxGrpc.createStub( - opts.fallback ? - (protos as protobuf.Root).lookupService('google.showcase.v1beta1.Messaging') : + this.messagingStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.Messaging') : // tslint:disable-next-line no-any - (protos as any).google.showcase.v1beta1.Messaging, - opts) as Promise<{[method: string]: Function}>; + (this._protos as any).google.showcase.v1beta1.Messaging, + this._opts) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -235,9 +261,9 @@ export class MessagingClient { throw err; }); - const apiCall = gaxModule.createApiCall( + const apiCall = this._gaxModule.createApiCall( innerCallPromise, - defaults[methodName], + this._defaults[methodName], this._descriptors.page[methodName] || this._descriptors.stream[methodName] || this._descriptors.longrunning[methodName] @@ -251,6 +277,8 @@ export class MessagingClient { return apiCall(argument, callOptions, callback); }; } + + return this.messagingStub; } /** @@ -352,6 +380,7 @@ export class MessagingClient { options = optionsOrCallback as gax.CallOptions; } options = options || {}; + this.initialize(); return this._innerApiCalls.createRoom(request, options, callback); } getRoom( @@ -411,6 +440,7 @@ export class MessagingClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.getRoom(request, options, callback); } updateRoom( @@ -473,6 +503,7 @@ export class MessagingClient { ] = gax.routingHeader.fromParams({ 'room.name': request.room!.name || '', }); + this.initialize(); return this._innerApiCalls.updateRoom(request, options, callback); } deleteRoom( @@ -532,6 +563,7 @@ export class MessagingClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.deleteRoom(request, options, callback); } createBlurb( @@ -596,6 +628,7 @@ export class MessagingClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.createBlurb(request, options, callback); } getBlurb( @@ -655,6 +688,7 @@ export class MessagingClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.getBlurb(request, options, callback); } updateBlurb( @@ -717,6 +751,7 @@ export class MessagingClient { ] = gax.routingHeader.fromParams({ 'blurb.name': request.blurb!.name || '', }); + this.initialize(); return this._innerApiCalls.updateBlurb(request, options, callback); } deleteBlurb( @@ -776,6 +811,7 @@ export class MessagingClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.deleteBlurb(request, options, callback); } @@ -807,6 +843,7 @@ export class MessagingClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.streamBlurbs(request, options); } @@ -843,6 +880,7 @@ export class MessagingClient { optionsOrCallback = {}; } const options = optionsOrCallback as gax.CallOptions; + this.initialize(); return this._innerApiCalls.sendBlurbs(null, options, callback); } @@ -861,7 +899,8 @@ export class MessagingClient { */ connect( options?: gax.CallOptions): - gax.CancellableStream{ + gax.CancellableStream { + this.initialize(); return this._innerApiCalls.connect(options); } @@ -937,6 +976,7 @@ export class MessagingClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.searchBlurbs(request, options, callback); } listRooms( @@ -1009,6 +1049,7 @@ export class MessagingClient { options = optionsOrCallback as gax.CallOptions; } options = options || {}; + this.initialize(); return this._innerApiCalls.listRooms(request, options, callback); } @@ -1046,6 +1087,7 @@ export class MessagingClient { request = request || {}; options = options || {}; const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listRooms.createStream( this._innerApiCalls.listRooms as gax.GaxCall, request, @@ -1133,6 +1175,7 @@ export class MessagingClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.listBlurbs(request, options, callback); } @@ -1180,6 +1223,7 @@ export class MessagingClient { 'parent': request.parent || '', }); const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listBlurbs.createStream( this._innerApiCalls.listBlurbs as gax.GaxCall, request, @@ -1422,8 +1466,9 @@ export class MessagingClient { * The client will no longer be usable and all future behavior is undefined. */ close(): Promise { + this.initialize(); if (!this._terminated) { - return this.messagingStub.then(stub => { + return this.messagingStub!.then(stub => { this._terminated = true; stub.close(); }); diff --git a/baselines/showcase/src/v1beta1/testing_client.ts.baseline b/baselines/showcase/src/v1beta1/testing_client.ts.baseline index 4a4afa5b4..584cadb85 100644 --- a/baselines/showcase/src/v1beta1/testing_client.ts.baseline +++ b/baselines/showcase/src/v1beta1/testing_client.ts.baseline @@ -37,8 +37,13 @@ export class TestingClient { private _innerApiCalls: {[name: string]: Function}; private _pathTemplates: {[name: string]: gax.PathTemplate}; private _terminated = false; + private _opts: ClientOptions; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; auth: gax.GoogleAuth; - testingStub: Promise<{[name: string]: Function}>; + testingStub?: Promise<{[name: string]: Function}>; /** * Construct an instance of TestingClient. @@ -91,28 +96,31 @@ export class TestingClient { // If we are in browser, we are already using fallback because of the // "browser" field in package.json. // But if we were explicitly requested to use fallback, let's do it now. - const gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; + this._gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; // Create a `gaxGrpc` object, with any grpc-specific options // sent to the client. opts.scopes = (this.constructor as typeof TestingClient).scopes; - const gaxGrpc = new gaxModule.GrpcClient(opts); + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (gaxGrpc.auth as gax.GoogleAuth); + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); // Determine the client header string. const clientHeader = [ - `gax/${gaxModule.version}`, + `gax/${this._gaxModule.version}`, `gapic/${version}`, ]; if (typeof process !== 'undefined' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { - clientHeader.push(`gl-web/${gaxModule.version}`); + clientHeader.push(`gl-web/${this._gaxModule.version}`); } if (!opts.fallback) { - clientHeader.push(`grpc/${gaxGrpc.grpcVersion}`); + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { clientHeader.push(`${opts.libName}/${opts.libVersion}`); @@ -122,7 +130,7 @@ export class TestingClient { // For browsers, pass the JSON content. const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); - const protos = gaxGrpc.loadProto( + this._protos = this._gaxGrpc.loadProto( opts.fallback ? require("../../protos/protos.json") : nodejsProtoPath @@ -132,25 +140,25 @@ export class TestingClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this._pathTemplates = { - blueprintPathTemplate: new gaxModule.PathTemplate( + blueprintPathTemplate: new this._gaxModule.PathTemplate( 'sessions/{session}/tests/{test}/blueprints/{blueprint}' ), - roomPathTemplate: new gaxModule.PathTemplate( + roomPathTemplate: new this._gaxModule.PathTemplate( 'rooms/{room_id}' ), - roomIdBlurbIdPathTemplate: new gaxModule.PathTemplate( + roomIdBlurbIdPathTemplate: new this._gaxModule.PathTemplate( 'rooms/{room_id}/blurbs/{blurb_id}' ), - sessionPathTemplate: new gaxModule.PathTemplate( + sessionPathTemplate: new this._gaxModule.PathTemplate( 'sessions/{session}' ), - testPathTemplate: new gaxModule.PathTemplate( + testPathTemplate: new this._gaxModule.PathTemplate( 'sessions/{session}/tests/{test}' ), - userPathTemplate: new gaxModule.PathTemplate( + userPathTemplate: new this._gaxModule.PathTemplate( 'users/{user_id}' ), - userIdBlurbIdPathTemplate: new gaxModule.PathTemplate( + userIdBlurbIdPathTemplate: new this._gaxModule.PathTemplate( 'user/{user_id}/profile/blurbs/{blurb_id}' ), }; @@ -160,13 +168,13 @@ export class TestingClient { // pages). Denote the keys used for pagination and results. this._descriptors.page = { listSessions: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'sessions'), + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'sessions'), listTests: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'tests') + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'tests') }; // Put together the default options sent with requests. - const defaults = gaxGrpc.constructSettings( + this._defaults = this._gaxGrpc.constructSettings( 'google.showcase.v1beta1.Testing', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); @@ -174,15 +182,33 @@ export class TestingClient { // of calling the API is handled in `google-gax`, with this code // merely providing the destination and request information. this._innerApiCalls = {}; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.testingStub) { + return this.testingStub; + } // Put together the "service stub" for // google.showcase.v1beta1.Testing. - this.testingStub = gaxGrpc.createStub( - opts.fallback ? - (protos as protobuf.Root).lookupService('google.showcase.v1beta1.Testing') : + this.testingStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.showcase.v1beta1.Testing') : // tslint:disable-next-line no-any - (protos as any).google.showcase.v1beta1.Testing, - opts) as Promise<{[method: string]: Function}>; + (this._protos as any).google.showcase.v1beta1.Testing, + this._opts) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -201,9 +227,9 @@ export class TestingClient { throw err; }); - const apiCall = gaxModule.createApiCall( + const apiCall = this._gaxModule.createApiCall( innerCallPromise, - defaults[methodName], + this._defaults[methodName], this._descriptors.page[methodName] || this._descriptors.stream[methodName] || this._descriptors.longrunning[methodName] @@ -217,6 +243,8 @@ export class TestingClient { return apiCall(argument, callOptions, callback); }; } + + return this.testingStub; } /** @@ -320,6 +348,7 @@ export class TestingClient { options = optionsOrCallback as gax.CallOptions; } options = options || {}; + this.initialize(); return this._innerApiCalls.createSession(request, options, callback); } getSession( @@ -379,6 +408,7 @@ export class TestingClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.getSession(request, options, callback); } deleteSession( @@ -438,6 +468,7 @@ export class TestingClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.deleteSession(request, options, callback); } reportSession( @@ -499,6 +530,7 @@ export class TestingClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.reportSession(request, options, callback); } deleteTest( @@ -563,6 +595,7 @@ export class TestingClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.deleteTest(request, options, callback); } verifyTest( @@ -629,6 +662,7 @@ export class TestingClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.verifyTest(request, options, callback); } @@ -699,6 +733,7 @@ export class TestingClient { options = optionsOrCallback as gax.CallOptions; } options = options || {}; + this.initialize(); return this._innerApiCalls.listSessions(request, options, callback); } @@ -733,6 +768,7 @@ export class TestingClient { request = request || {}; options = options || {}; const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listSessions.createStream( this._innerApiCalls.listSessions as gax.GaxCall, request, @@ -815,6 +851,7 @@ export class TestingClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.listTests(request, options, callback); } @@ -858,6 +895,7 @@ export class TestingClient { 'parent': request.parent || '', }); const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listTests.createStream( this._innerApiCalls.listTests as gax.GaxCall, request, @@ -1100,8 +1138,9 @@ export class TestingClient { * The client will no longer be usable and all future behavior is undefined. */ close(): Promise { + this.initialize(); if (!this._terminated) { - return this.testingStub.then(stub => { + return this.testingStub!.then(stub => { this._terminated = true; stub.close(); }); diff --git a/baselines/showcase/test/gapic-echo-v1beta1.ts.baseline b/baselines/showcase/test/gapic-echo-v1beta1.ts.baseline index 80b20ef95..8d746c59f 100644 --- a/baselines/showcase/test/gapic-echo-v1beta1.ts.baseline +++ b/baselines/showcase/test/gapic-echo-v1beta1.ts.baseline @@ -132,12 +132,30 @@ describe('v1beta1.EchoClient', () => { }); assert(client); }); + it('has initialize method and supports deferred initialization', async () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.echoStub, undefined); + await client.initialize(); + assert(client.echoStub); + }); + it('has close method', () => { + const client = new echoModule.v1beta1.EchoClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.close(); + }); describe('echo', () => { it('invokes echo without error', done => { const client = new echoModule.v1beta1.EchoClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IEchoRequest = {}; // Mock response @@ -160,6 +178,8 @@ describe('v1beta1.EchoClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IEchoRequest = {}; // Mock response @@ -184,6 +204,8 @@ describe('v1beta1.EchoClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IBlockRequest = {}; // Mock response @@ -206,6 +228,8 @@ describe('v1beta1.EchoClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IBlockRequest = {}; // Mock response @@ -230,6 +254,8 @@ describe('v1beta1.EchoClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IWaitRequest = {}; // Mock response @@ -255,6 +281,8 @@ describe('v1beta1.EchoClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IWaitRequest = {}; // Mock response @@ -283,6 +311,8 @@ describe('v1beta1.EchoClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IExpandRequest = {}; // Mock response @@ -304,6 +334,8 @@ describe('v1beta1.EchoClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IExpandRequest = {}; // Mock response @@ -328,6 +360,8 @@ describe('v1beta1.EchoClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IEchoRequest = {}; // Mock response @@ -347,6 +381,8 @@ describe('v1beta1.EchoClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IEchoRequest = {}; // Mock response @@ -369,6 +405,8 @@ describe('v1beta1.EchoClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IPagedExpandRequest = {}; // Mock response @@ -391,6 +429,8 @@ describe('v1beta1.EchoClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IPagedExpandRequest = {}; // Mock response diff --git a/baselines/showcase/test/gapic-identity-v1beta1.ts.baseline b/baselines/showcase/test/gapic-identity-v1beta1.ts.baseline index 8c1aaa3f4..e3521358c 100644 --- a/baselines/showcase/test/gapic-identity-v1beta1.ts.baseline +++ b/baselines/showcase/test/gapic-identity-v1beta1.ts.baseline @@ -78,12 +78,30 @@ describe('v1beta1.IdentityClient', () => { }); assert(client); }); + it('has initialize method and supports deferred initialization', async () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.identityStub, undefined); + await client.initialize(); + assert(client.identityStub); + }); + it('has close method', () => { + const client = new identityModule.v1beta1.IdentityClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.close(); + }); describe('createUser', () => { it('invokes createUser without error', done => { const client = new identityModule.v1beta1.IdentityClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.ICreateUserRequest = {}; // Mock response @@ -106,6 +124,8 @@ describe('v1beta1.IdentityClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.ICreateUserRequest = {}; // Mock response @@ -130,6 +150,8 @@ describe('v1beta1.IdentityClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IGetUserRequest = {}; request.name = ''; @@ -153,6 +175,8 @@ describe('v1beta1.IdentityClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IGetUserRequest = {}; request.name = ''; @@ -178,6 +202,8 @@ describe('v1beta1.IdentityClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IUpdateUserRequest = {}; request.user = {}; @@ -202,6 +228,8 @@ describe('v1beta1.IdentityClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IUpdateUserRequest = {}; request.user = {}; @@ -228,6 +256,8 @@ describe('v1beta1.IdentityClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IDeleteUserRequest = {}; request.name = ''; @@ -251,6 +281,8 @@ describe('v1beta1.IdentityClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IDeleteUserRequest = {}; request.name = ''; @@ -276,6 +308,8 @@ describe('v1beta1.IdentityClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IListUsersRequest = {}; // Mock response @@ -298,6 +332,8 @@ describe('v1beta1.IdentityClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IListUsersRequest = {}; // Mock response diff --git a/baselines/showcase/test/gapic-messaging-v1beta1.ts.baseline b/baselines/showcase/test/gapic-messaging-v1beta1.ts.baseline index 2d4a2deed..5cb3657f7 100644 --- a/baselines/showcase/test/gapic-messaging-v1beta1.ts.baseline +++ b/baselines/showcase/test/gapic-messaging-v1beta1.ts.baseline @@ -132,12 +132,30 @@ describe('v1beta1.MessagingClient', () => { }); assert(client); }); + it('has initialize method and supports deferred initialization', async () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.messagingStub, undefined); + await client.initialize(); + assert(client.messagingStub); + }); + it('has close method', () => { + const client = new messagingModule.v1beta1.MessagingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.close(); + }); describe('createRoom', () => { it('invokes createRoom without error', done => { const client = new messagingModule.v1beta1.MessagingClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.ICreateRoomRequest = {}; // Mock response @@ -160,6 +178,8 @@ describe('v1beta1.MessagingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.ICreateRoomRequest = {}; // Mock response @@ -184,6 +204,8 @@ describe('v1beta1.MessagingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IGetRoomRequest = {}; request.name = ''; @@ -207,6 +229,8 @@ describe('v1beta1.MessagingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IGetRoomRequest = {}; request.name = ''; @@ -232,6 +256,8 @@ describe('v1beta1.MessagingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IUpdateRoomRequest = {}; request.room = {}; @@ -256,6 +282,8 @@ describe('v1beta1.MessagingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IUpdateRoomRequest = {}; request.room = {}; @@ -282,6 +310,8 @@ describe('v1beta1.MessagingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IDeleteRoomRequest = {}; request.name = ''; @@ -305,6 +335,8 @@ describe('v1beta1.MessagingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IDeleteRoomRequest = {}; request.name = ''; @@ -330,6 +362,8 @@ describe('v1beta1.MessagingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.ICreateBlurbRequest = {}; request.parent = ''; @@ -353,6 +387,8 @@ describe('v1beta1.MessagingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.ICreateBlurbRequest = {}; request.parent = ''; @@ -378,6 +414,8 @@ describe('v1beta1.MessagingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IGetBlurbRequest = {}; request.name = ''; @@ -401,6 +439,8 @@ describe('v1beta1.MessagingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IGetBlurbRequest = {}; request.name = ''; @@ -426,6 +466,8 @@ describe('v1beta1.MessagingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IUpdateBlurbRequest = {}; request.blurb = {}; @@ -450,6 +492,8 @@ describe('v1beta1.MessagingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IUpdateBlurbRequest = {}; request.blurb = {}; @@ -476,6 +520,8 @@ describe('v1beta1.MessagingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IDeleteBlurbRequest = {}; request.name = ''; @@ -499,6 +545,8 @@ describe('v1beta1.MessagingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IDeleteBlurbRequest = {}; request.name = ''; @@ -524,6 +572,8 @@ describe('v1beta1.MessagingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.ISearchBlurbsRequest = {}; request.parent = ''; @@ -550,6 +600,8 @@ describe('v1beta1.MessagingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.ISearchBlurbsRequest = {}; request.parent = ''; @@ -579,6 +631,8 @@ describe('v1beta1.MessagingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IStreamBlurbsRequest = {}; request.name = ''; @@ -601,6 +655,8 @@ describe('v1beta1.MessagingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IStreamBlurbsRequest = {}; request.name = ''; @@ -626,6 +682,8 @@ describe('v1beta1.MessagingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IConnectRequest = {}; // Mock response @@ -645,6 +703,8 @@ describe('v1beta1.MessagingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IConnectRequest = {}; // Mock response @@ -667,6 +727,8 @@ describe('v1beta1.MessagingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IListRoomsRequest = {}; // Mock response @@ -689,6 +751,8 @@ describe('v1beta1.MessagingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IListRoomsRequest = {}; // Mock response @@ -713,6 +777,8 @@ describe('v1beta1.MessagingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IListBlurbsRequest = {}; request.parent = ''; @@ -736,6 +802,8 @@ describe('v1beta1.MessagingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IListBlurbsRequest = {}; request.parent = ''; diff --git a/baselines/showcase/test/gapic-testing-v1beta1.ts.baseline b/baselines/showcase/test/gapic-testing-v1beta1.ts.baseline index 3c27cc0ba..81cb1e560 100644 --- a/baselines/showcase/test/gapic-testing-v1beta1.ts.baseline +++ b/baselines/showcase/test/gapic-testing-v1beta1.ts.baseline @@ -78,12 +78,30 @@ describe('v1beta1.TestingClient', () => { }); assert(client); }); + it('has initialize method and supports deferred initialization', async () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.testingStub, undefined); + await client.initialize(); + assert(client.testingStub); + }); + it('has close method', () => { + const client = new testingModule.v1beta1.TestingClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.close(); + }); describe('createSession', () => { it('invokes createSession without error', done => { const client = new testingModule.v1beta1.TestingClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.ICreateSessionRequest = {}; // Mock response @@ -106,6 +124,8 @@ describe('v1beta1.TestingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.ICreateSessionRequest = {}; // Mock response @@ -130,6 +150,8 @@ describe('v1beta1.TestingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IGetSessionRequest = {}; request.name = ''; @@ -153,6 +175,8 @@ describe('v1beta1.TestingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IGetSessionRequest = {}; request.name = ''; @@ -178,6 +202,8 @@ describe('v1beta1.TestingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IDeleteSessionRequest = {}; request.name = ''; @@ -201,6 +227,8 @@ describe('v1beta1.TestingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IDeleteSessionRequest = {}; request.name = ''; @@ -226,6 +254,8 @@ describe('v1beta1.TestingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IReportSessionRequest = {}; request.name = ''; @@ -249,6 +279,8 @@ describe('v1beta1.TestingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IReportSessionRequest = {}; request.name = ''; @@ -274,6 +306,8 @@ describe('v1beta1.TestingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IDeleteTestRequest = {}; request.name = ''; @@ -297,6 +331,8 @@ describe('v1beta1.TestingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IDeleteTestRequest = {}; request.name = ''; @@ -322,6 +358,8 @@ describe('v1beta1.TestingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IVerifyTestRequest = {}; request.name = ''; @@ -345,6 +383,8 @@ describe('v1beta1.TestingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IVerifyTestRequest = {}; request.name = ''; @@ -370,6 +410,8 @@ describe('v1beta1.TestingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IListSessionsRequest = {}; // Mock response @@ -392,6 +434,8 @@ describe('v1beta1.TestingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IListSessionsRequest = {}; // Mock response @@ -416,6 +460,8 @@ describe('v1beta1.TestingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IListTestsRequest = {}; request.parent = ''; @@ -439,6 +485,8 @@ describe('v1beta1.TestingClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.showcase.v1beta1.IListTestsRequest = {}; request.parent = ''; diff --git a/baselines/texttospeech/src/v1/text_to_speech_client.ts.baseline b/baselines/texttospeech/src/v1/text_to_speech_client.ts.baseline index 414e83565..8306d9229 100644 --- a/baselines/texttospeech/src/v1/text_to_speech_client.ts.baseline +++ b/baselines/texttospeech/src/v1/text_to_speech_client.ts.baseline @@ -34,8 +34,13 @@ export class TextToSpeechClient { private _descriptors: Descriptors = {page: {}, stream: {}, longrunning: {}}; private _innerApiCalls: {[name: string]: Function}; private _terminated = false; + private _opts: ClientOptions; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; auth: gax.GoogleAuth; - textToSpeechStub: Promise<{[name: string]: Function}>; + textToSpeechStub?: Promise<{[name: string]: Function}>; /** * Construct an instance of TextToSpeechClient. @@ -88,28 +93,31 @@ export class TextToSpeechClient { // If we are in browser, we are already using fallback because of the // "browser" field in package.json. // But if we were explicitly requested to use fallback, let's do it now. - const gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; + this._gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; // Create a `gaxGrpc` object, with any grpc-specific options // sent to the client. opts.scopes = (this.constructor as typeof TextToSpeechClient).scopes; - const gaxGrpc = new gaxModule.GrpcClient(opts); + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (gaxGrpc.auth as gax.GoogleAuth); + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); // Determine the client header string. const clientHeader = [ - `gax/${gaxModule.version}`, + `gax/${this._gaxModule.version}`, `gapic/${version}`, ]; if (typeof process !== 'undefined' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { - clientHeader.push(`gl-web/${gaxModule.version}`); + clientHeader.push(`gl-web/${this._gaxModule.version}`); } if (!opts.fallback) { - clientHeader.push(`grpc/${gaxGrpc.grpcVersion}`); + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { clientHeader.push(`${opts.libName}/${opts.libVersion}`); @@ -119,14 +127,14 @@ export class TextToSpeechClient { // For browsers, pass the JSON content. const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); - const protos = gaxGrpc.loadProto( + this._protos = this._gaxGrpc.loadProto( opts.fallback ? require("../../protos/protos.json") : nodejsProtoPath ); // Put together the default options sent with requests. - const defaults = gaxGrpc.constructSettings( + this._defaults = this._gaxGrpc.constructSettings( 'google.cloud.texttospeech.v1.TextToSpeech', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); @@ -134,15 +142,33 @@ export class TextToSpeechClient { // of calling the API is handled in `google-gax`, with this code // merely providing the destination and request information. this._innerApiCalls = {}; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.textToSpeechStub) { + return this.textToSpeechStub; + } // Put together the "service stub" for // google.cloud.texttospeech.v1.TextToSpeech. - this.textToSpeechStub = gaxGrpc.createStub( - opts.fallback ? - (protos as protobuf.Root).lookupService('google.cloud.texttospeech.v1.TextToSpeech') : + this.textToSpeechStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.cloud.texttospeech.v1.TextToSpeech') : // tslint:disable-next-line no-any - (protos as any).google.cloud.texttospeech.v1.TextToSpeech, - opts) as Promise<{[method: string]: Function}>; + (this._protos as any).google.cloud.texttospeech.v1.TextToSpeech, + this._opts) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -161,9 +187,9 @@ export class TextToSpeechClient { throw err; }); - const apiCall = gaxModule.createApiCall( + const apiCall = this._gaxModule.createApiCall( innerCallPromise, - defaults[methodName], + this._defaults[methodName], this._descriptors.page[methodName] || this._descriptors.stream[methodName] || this._descriptors.longrunning[methodName] @@ -177,6 +203,8 @@ export class TextToSpeechClient { return apiCall(argument, callOptions, callback); }; } + + return this.textToSpeechStub; } /** @@ -287,6 +315,7 @@ export class TextToSpeechClient { options = optionsOrCallback as gax.CallOptions; } options = options || {}; + this.initialize(); return this._innerApiCalls.listVoices(request, options, callback); } synthesizeSpeech( @@ -344,6 +373,7 @@ export class TextToSpeechClient { options = optionsOrCallback as gax.CallOptions; } options = options || {}; + this.initialize(); return this._innerApiCalls.synthesizeSpeech(request, options, callback); } @@ -354,8 +384,9 @@ export class TextToSpeechClient { * The client will no longer be usable and all future behavior is undefined. */ close(): Promise { + this.initialize(); if (!this._terminated) { - return this.textToSpeechStub.then(stub => { + return this.textToSpeechStub!.then(stub => { this._terminated = true; stub.close(); }); diff --git a/baselines/texttospeech/test/gapic-text_to_speech-v1.ts.baseline b/baselines/texttospeech/test/gapic-text_to_speech-v1.ts.baseline index 0ff0b1c89..df81845b3 100644 --- a/baselines/texttospeech/test/gapic-text_to_speech-v1.ts.baseline +++ b/baselines/texttospeech/test/gapic-text_to_speech-v1.ts.baseline @@ -78,12 +78,30 @@ describe('v1.TextToSpeechClient', () => { }); assert(client); }); + it('has initialize method and supports deferred initialization', async () => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.textToSpeechStub, undefined); + await client.initialize(); + assert(client.textToSpeechStub); + }); + it('has close method', () => { + const client = new texttospeechModule.v1.TextToSpeechClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.close(); + }); describe('listVoices', () => { it('invokes listVoices without error', done => { const client = new texttospeechModule.v1.TextToSpeechClient({ credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.texttospeech.v1.IListVoicesRequest = {}; // Mock response @@ -106,6 +124,8 @@ describe('v1.TextToSpeechClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.texttospeech.v1.IListVoicesRequest = {}; // Mock response @@ -130,6 +150,8 @@ describe('v1.TextToSpeechClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest = {}; // Mock response @@ -152,6 +174,8 @@ describe('v1.TextToSpeechClient', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request const request: protosTypes.google.cloud.texttospeech.v1.ISynthesizeSpeechRequest = {}; // Mock response diff --git a/baselines/translate/src/v3beta1/translation_service_client.ts.baseline b/baselines/translate/src/v3beta1/translation_service_client.ts.baseline index 57328a1e8..282c8d5e7 100644 --- a/baselines/translate/src/v3beta1/translation_service_client.ts.baseline +++ b/baselines/translate/src/v3beta1/translation_service_client.ts.baseline @@ -36,9 +36,14 @@ export class TranslationServiceClient { private _innerApiCalls: {[name: string]: Function}; private _pathTemplates: {[name: string]: gax.PathTemplate}; private _terminated = false; + private _opts: ClientOptions; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; auth: gax.GoogleAuth; operationsClient: gax.OperationsClient; - translationServiceStub: Promise<{[name: string]: Function}>; + translationServiceStub?: Promise<{[name: string]: Function}>; /** * Construct an instance of TranslationServiceClient. @@ -91,28 +96,31 @@ export class TranslationServiceClient { // If we are in browser, we are already using fallback because of the // "browser" field in package.json. // But if we were explicitly requested to use fallback, let's do it now. - const gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; + this._gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; // Create a `gaxGrpc` object, with any grpc-specific options // sent to the client. opts.scopes = (this.constructor as typeof TranslationServiceClient).scopes; - const gaxGrpc = new gaxModule.GrpcClient(opts); + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (gaxGrpc.auth as gax.GoogleAuth); + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); // Determine the client header string. const clientHeader = [ - `gax/${gaxModule.version}`, + `gax/${this._gaxModule.version}`, `gapic/${version}`, ]; if (typeof process !== 'undefined' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { - clientHeader.push(`gl-web/${gaxModule.version}`); + clientHeader.push(`gl-web/${this._gaxModule.version}`); } if (!opts.fallback) { - clientHeader.push(`grpc/${gaxGrpc.grpcVersion}`); + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { clientHeader.push(`${opts.libName}/${opts.libVersion}`); @@ -122,7 +130,7 @@ export class TranslationServiceClient { // For browsers, pass the JSON content. const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); - const protos = gaxGrpc.loadProto( + this._protos = this._gaxGrpc.loadProto( opts.fallback ? require("../../protos/protos.json") : nodejsProtoPath @@ -132,10 +140,10 @@ export class TranslationServiceClient { // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this._pathTemplates = { - glossaryPathTemplate: new gaxModule.PathTemplate( + glossaryPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/locations/{location}/glossaries/{glossary}' ), - locationPathTemplate: new gaxModule.PathTemplate( + locationPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/locations/{location}' ), }; @@ -145,19 +153,19 @@ export class TranslationServiceClient { // pages). Denote the keys used for pagination and results. this._descriptors.page = { listGlossaries: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'glossaries') + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', 'glossaries') }; // This API contains "long-running operations", which return a // an Operation object that allows for tracking of the operation, // rather than holding a request open. const protoFilesRoot = opts.fallback? - gaxModule.protobuf.Root.fromJSON(require("../../protos/protos.json")) : - gaxModule.protobuf.loadSync(nodejsProtoPath); + this._gaxModule.protobuf.Root.fromJSON(require("../../protos/protos.json")) : + this._gaxModule.protobuf.loadSync(nodejsProtoPath); - this.operationsClient = gaxModule.lro({ + this.operationsClient = this._gaxModule.lro({ auth: this.auth, - grpc: 'grpc' in gaxGrpc ? gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined }).operationsClient(opts); const batchTranslateTextResponse = protoFilesRoot.lookup( '.google.cloud.translation.v3beta1.BatchTranslateResponse') as gax.protobuf.Type; @@ -173,22 +181,22 @@ export class TranslationServiceClient { '.google.cloud.translation.v3beta1.DeleteGlossaryMetadata') as gax.protobuf.Type; this._descriptors.longrunning = { - batchTranslateText: new gaxModule.LongrunningDescriptor( + batchTranslateText: new this._gaxModule.LongrunningDescriptor( this.operationsClient, batchTranslateTextResponse.decode.bind(batchTranslateTextResponse), batchTranslateTextMetadata.decode.bind(batchTranslateTextMetadata)), - createGlossary: new gaxModule.LongrunningDescriptor( + createGlossary: new this._gaxModule.LongrunningDescriptor( this.operationsClient, createGlossaryResponse.decode.bind(createGlossaryResponse), createGlossaryMetadata.decode.bind(createGlossaryMetadata)), - deleteGlossary: new gaxModule.LongrunningDescriptor( + deleteGlossary: new this._gaxModule.LongrunningDescriptor( this.operationsClient, deleteGlossaryResponse.decode.bind(deleteGlossaryResponse), deleteGlossaryMetadata.decode.bind(deleteGlossaryMetadata)) }; // Put together the default options sent with requests. - const defaults = gaxGrpc.constructSettings( + this._defaults = this._gaxGrpc.constructSettings( 'google.cloud.translation.v3beta1.TranslationService', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); @@ -196,15 +204,33 @@ export class TranslationServiceClient { // of calling the API is handled in `google-gax`, with this code // merely providing the destination and request information. this._innerApiCalls = {}; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.translationServiceStub) { + return this.translationServiceStub; + } // Put together the "service stub" for // google.cloud.translation.v3beta1.TranslationService. - this.translationServiceStub = gaxGrpc.createStub( - opts.fallback ? - (protos as protobuf.Root).lookupService('google.cloud.translation.v3beta1.TranslationService') : + this.translationServiceStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.cloud.translation.v3beta1.TranslationService') : // tslint:disable-next-line no-any - (protos as any).google.cloud.translation.v3beta1.TranslationService, - opts) as Promise<{[method: string]: Function}>; + (this._protos as any).google.cloud.translation.v3beta1.TranslationService, + this._opts) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -223,9 +249,9 @@ export class TranslationServiceClient { throw err; }); - const apiCall = gaxModule.createApiCall( + const apiCall = this._gaxModule.createApiCall( innerCallPromise, - defaults[methodName], + this._defaults[methodName], this._descriptors.page[methodName] || this._descriptors.stream[methodName] || this._descriptors.longrunning[methodName] @@ -239,6 +265,8 @@ export class TranslationServiceClient { return apiCall(argument, callOptions, callback); }; } + + return this.translationServiceStub; } /** @@ -410,6 +438,7 @@ export class TranslationServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.translateText(request, options, callback); } detectLanguage( @@ -503,6 +532,7 @@ export class TranslationServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.detectLanguage(request, options, callback); } getSupportedLanguages( @@ -593,6 +623,7 @@ export class TranslationServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.getSupportedLanguages(request, options, callback); } getGlossary( @@ -653,6 +684,7 @@ export class TranslationServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.getGlossary(request, options, callback); } @@ -769,6 +801,7 @@ export class TranslationServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.batchTranslateText(request, options, callback); } createGlossary( @@ -831,6 +864,7 @@ export class TranslationServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.createGlossary(request, options, callback); } deleteGlossary( @@ -892,6 +926,7 @@ export class TranslationServiceClient { ] = gax.routingHeader.fromParams({ 'name': request.name || '', }); + this.initialize(); return this._innerApiCalls.deleteGlossary(request, options, callback); } listGlossaries( @@ -979,6 +1014,7 @@ export class TranslationServiceClient { ] = gax.routingHeader.fromParams({ 'parent': request.parent || '', }); + this.initialize(); return this._innerApiCalls.listGlossaries(request, options, callback); } @@ -1030,6 +1066,7 @@ export class TranslationServiceClient { 'parent': request.parent || '', }); const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.listGlossaries.createStream( this._innerApiCalls.listGlossaries as gax.GaxCall, request, @@ -1131,8 +1168,9 @@ export class TranslationServiceClient { * The client will no longer be usable and all future behavior is undefined. */ close(): Promise { + this.initialize(); if (!this._terminated) { - return this.translationServiceStub.then(stub => { + return this.translationServiceStub!.then(stub => { this._terminated = true; stub.close(); }); diff --git a/baselines/translate/test/gapic-translation_service-v3beta1.ts.baseline b/baselines/translate/test/gapic-translation_service-v3beta1.ts.baseline index 63224dcf4..a73aadfea 100644 --- a/baselines/translate/test/gapic-translation_service-v3beta1.ts.baseline +++ b/baselines/translate/test/gapic-translation_service-v3beta1.ts.baseline @@ -96,12 +96,30 @@ describe('v3beta1.TranslationServiceClient', () => { }); 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 = ''; @@ -125,6 +143,8 @@ describe('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 = ''; @@ -150,6 +170,8 @@ describe('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 = ''; @@ -173,6 +195,8 @@ describe('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 = ''; @@ -198,6 +222,8 @@ describe('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 = ''; @@ -221,6 +247,8 @@ describe('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 = ''; @@ -246,6 +274,8 @@ describe('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 = ''; @@ -269,6 +299,8 @@ describe('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 = ''; @@ -294,6 +326,8 @@ describe('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 = ''; @@ -320,6 +354,8 @@ describe('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 = ''; @@ -349,6 +385,8 @@ describe('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 = ''; @@ -375,6 +413,8 @@ describe('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 = ''; @@ -404,6 +444,8 @@ describe('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 = ''; @@ -430,6 +472,8 @@ describe('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 = ''; @@ -459,6 +503,8 @@ describe('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 = ''; @@ -482,6 +528,8 @@ describe('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 = ''; diff --git a/templates/typescript_gapic/src/$version/$service_client.ts.njk b/templates/typescript_gapic/src/$version/$service_client.ts.njk index 8b0781e08..36fb2c5e0 100644 --- a/templates/typescript_gapic/src/$version/$service_client.ts.njk +++ b/templates/typescript_gapic/src/$version/$service_client.ts.njk @@ -45,11 +45,16 @@ export class {{ service.name }}Client { private _pathTemplates: {[name: string]: gax.PathTemplate}; {%- endif %} private _terminated = false; + private _opts: ClientOptions; + private _gaxModule: typeof gax | typeof gax.fallback; + private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; + private _protos: {}; + private _defaults: {[method: string]: gax.CallSettings}; auth: gax.GoogleAuth; {%- if (service.longRunning.length > 0) %} operationsClient: gax.OperationsClient; {%- endif %} - {{ service.name.toCamelCase() }}Stub: Promise<{[name: string]: Function}>; + {{ service.name.toCamelCase() }}Stub?: Promise<{[name: string]: Function}>; /** * Construct an instance of {{ service.name }}Client. @@ -102,28 +107,31 @@ export class {{ service.name }}Client { // If we are in browser, we are already using fallback because of the // "browser" field in package.json. // But if we were explicitly requested to use fallback, let's do it now. - const gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; + this._gaxModule = !isBrowser && opts.fallback ? gax.fallback : gax; // Create a `gaxGrpc` object, with any grpc-specific options // sent to the client. opts.scopes = (this.constructor as typeof {{ service.name }}Client).scopes; - const gaxGrpc = new gaxModule.GrpcClient(opts); + this._gaxGrpc = new this._gaxModule.GrpcClient(opts); + + // Save options to use in initialize() method. + this._opts = opts; // Save the auth object to the client, for use by other methods. - this.auth = (gaxGrpc.auth as gax.GoogleAuth); + this.auth = (this._gaxGrpc.auth as gax.GoogleAuth); // Determine the client header string. const clientHeader = [ - `gax/${gaxModule.version}`, + `gax/${this._gaxModule.version}`, `gapic/${version}`, ]; if (typeof process !== 'undefined' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { - clientHeader.push(`gl-web/${gaxModule.version}`); + clientHeader.push(`gl-web/${this._gaxModule.version}`); } if (!opts.fallback) { - clientHeader.push(`grpc/${gaxGrpc.grpcVersion}`); + clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { clientHeader.push(`${opts.libName}/${opts.libVersion}`); @@ -133,7 +141,7 @@ export class {{ service.name }}Client { // For browsers, pass the JSON content. const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); - const protos = gaxGrpc.loadProto( + this._protos = this._gaxGrpc.loadProto( opts.fallback ? require("../../protos/protos.json") : nodejsProtoPath @@ -145,7 +153,7 @@ export class {{ service.name }}Client { // Create useful helper objects for these. this._pathTemplates = { {%- for template in service.pathTemplates %} - {{ template.name.toCamelCase() }}PathTemplate: new gaxModule.PathTemplate( + {{ template.name.toCamelCase() }}PathTemplate: new this._gaxModule.PathTemplate( '{{ template.pattern }}' ), {%- endfor %} @@ -162,7 +170,7 @@ export class {{ service.name }}Client { {%- for method in service.paging %} {{- pagingJoiner() }} {{ method.name.toCamelCase() }}: - new gaxModule.PageDescriptor('pageToken', 'nextPageToken', '{{ method.pagingFieldName.toCamelCase() }}') + new this._gaxModule.PageDescriptor('pageToken', 'nextPageToken', '{{ method.pagingFieldName.toCamelCase() }}') {%- endfor %} }; {%- endif %} @@ -175,7 +183,7 @@ export class {{ service.name }}Client { {%- set streamingJoiner = joiner() %} {%- for method in service.streaming %} {{- streamingJoiner() }} - {{ method.name.toCamelCase() }}: new gaxModule.StreamDescriptor(gax.StreamType.{{ method.streaming }}) + {{ method.name.toCamelCase() }}: new this._gaxModule.StreamDescriptor(gax.StreamType.{{ method.streaming }}) {%- endfor %} }; {%- endif %} @@ -185,12 +193,12 @@ export class {{ service.name }}Client { // an Operation object that allows for tracking of the operation, // rather than holding a request open. const protoFilesRoot = opts.fallback? - gaxModule.protobuf.Root.fromJSON(require("../../protos/protos.json")) : - gaxModule.protobuf.loadSync(nodejsProtoPath); + this._gaxModule.protobuf.Root.fromJSON(require("../../protos/protos.json")) : + this._gaxModule.protobuf.loadSync(nodejsProtoPath); - this.operationsClient = gaxModule.lro({ + this.operationsClient = this._gaxModule.lro({ auth: this.auth, - grpc: 'grpc' in gaxGrpc ? gaxGrpc.grpc : undefined + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined }).operationsClient(opts); {%- for method in service.longRunning %} @@ -204,7 +212,7 @@ export class {{ service.name }}Client { {%- set longRunningJoiner = joiner() %} {%- for method in service.longRunning %} {{- longRunningJoiner() }} - {{ method.name.toCamelCase() }}: new gaxModule.LongrunningDescriptor( + {{ method.name.toCamelCase() }}: new this._gaxModule.LongrunningDescriptor( this.operationsClient, {{ method.name.toCamelCase() }}Response.decode.bind({{ method.name.toCamelCase() }}Response), {{ method.name.toCamelCase() }}Metadata.decode.bind({{ method.name.toCamelCase() }}Metadata)) @@ -213,7 +221,7 @@ export class {{ service.name }}Client { {%- endif %} // Put together the default options sent with requests. - const defaults = gaxGrpc.constructSettings( + this._defaults = this._gaxGrpc.constructSettings( '{{ api.naming.protoPackage }}.{{ service.name }}', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); @@ -221,15 +229,33 @@ export class {{ service.name }}Client { // of calling the API is handled in `google-gax`, with this code // merely providing the destination and request information. this._innerApiCalls = {}; + } + + /** + * Initialize the client. + * Performs asynchronous operations (such as authentication) and prepares the client. + * This function will be called automatically when any class method is called for the + * first time, but if you need to initialize it before calling an actual method, + * feel free to call initialize() directly. + * + * You can await on this method if you want to make sure the client is initialized. + * + * @returns {Promise} A promise that resolves to an authenticated service stub. + */ + initialize() { + // If the client stub promise is already initialized, return immediately. + if (this.{{ service.name.toCamelCase() }}Stub) { + return this.{{ service.name.toCamelCase() }}Stub; + } // Put together the "service stub" for // {{api.naming.protoPackage}}.{{ service.name }}. - this.{{ service.name.toCamelCase() }}Stub = gaxGrpc.createStub( - opts.fallback ? - (protos as protobuf.Root).lookupService('{{api.naming.protoPackage}}.{{ service.name }}') : + this.{{ service.name.toCamelCase() }}Stub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('{{api.naming.protoPackage}}.{{ service.name }}') : // tslint:disable-next-line no-any - (protos as any).{{api.naming.protoPackage}}.{{ service.name }}, - opts) as Promise<{[method: string]: Function}>; + (this._protos as any).{{api.naming.protoPackage}}.{{ service.name }}, + this._opts) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides // and create an API call method for each. @@ -254,9 +280,9 @@ export class {{ service.name }}Client { throw err; }); - const apiCall = gaxModule.createApiCall( + const apiCall = this._gaxModule.createApiCall( innerCallPromise, - defaults[methodName], + this._defaults[methodName], this._descriptors.page[methodName] || this._descriptors.stream[methodName] || this._descriptors.longrunning[methodName] @@ -270,6 +296,8 @@ export class {{ service.name }}Client { return apiCall(argument, callOptions, callback); }; } + + return this.{{ service.name.toCamelCase() }}Stub; } /** @@ -373,6 +401,7 @@ export class {{ service.name }}Client { options = optionsOrCallback as gax.CallOptions; } {{ util.buildHeaderRequestParam(method) }} + this.initialize(); return this._innerApiCalls.{{ method.name.toCamelCase() }}(request, options, callback); } {%- endfor %} @@ -383,7 +412,8 @@ export class {{ service.name }}Client { */ {{ method.name.toCamelCase() }}( options?: gax.CallOptions): - gax.CancellableStream{ + gax.CancellableStream { + this.initialize(); return this._innerApiCalls.{{ method.name.toCamelCase() }}(options); } {%- elif method.serverStreaming %} @@ -396,6 +426,7 @@ export class {{ service.name }}Client { gax.CancellableStream{ request = request || {}; {{ util.buildHeaderRequestParam(method) }} + this.initialize(); return this._innerApiCalls.{{ method.name.toCamelCase() }}(request, options); } {%- elif method.clientStreaming %} @@ -426,6 +457,7 @@ export class {{ service.name }}Client { optionsOrCallback = {}; } const options = optionsOrCallback as gax.CallOptions; + this.initialize(); return this._innerApiCalls.{{ method.name.toCamelCase() }}(null, options, callback); } {%- endif %} @@ -471,6 +503,7 @@ export class {{ service.name }}Client { options = optionsOrCallback as gax.CallOptions; } {{ util.buildHeaderRequestParam(method) }} + this.initialize(); return this._innerApiCalls.{{ method.name.toCamelCase() }}(request, options, callback); } {%- endfor %} @@ -518,6 +551,7 @@ export class {{ service.name }}Client { options = optionsOrCallback as gax.CallOptions; } {{ util.buildHeaderRequestParam(method) }} + this.initialize(); return this._innerApiCalls.{{ method.name.toCamelCase() }}(request, options, callback); } @@ -531,6 +565,7 @@ export class {{ service.name }}Client { request = request || {}; {{ util.buildHeaderRequestParam(method) }} const callSettings = new gax.CallSettings(options); + this.initialize(); return this._descriptors.page.{{ method.name.toCamelCase() }}.createStream( this._innerApiCalls.{{ method.name.toCamelCase() }} as gax.GaxCall, request, @@ -586,8 +621,9 @@ export class {{ service.name }}Client { * The client will no longer be usable and all future behavior is undefined. */ close(): Promise { + this.initialize(); if (!this._terminated) { - return this.{{ service.name.toCamelCase() }}Stub.then(stub => { + return this.{{ service.name.toCamelCase() }}Stub!.then(stub => { this._terminated = true; stub.close(); }); diff --git a/templates/typescript_gapic/test/gapic-$service-$version.ts.njk b/templates/typescript_gapic/test/gapic-$service-$version.ts.njk index 84f3e4969..e1a7755cb 100644 --- a/templates/typescript_gapic/test/gapic-$service-$version.ts.njk +++ b/templates/typescript_gapic/test/gapic-$service-$version.ts.njk @@ -143,6 +143,22 @@ describe('{{ api.naming.version }}.{{ service.name }}Client', () => { }); assert(client); }); + it('has initialize method and supports deferred initialization', async () => { + const client = new {{ service.name.toLowerCase() }}Module.{{ api.naming.version }}.{{ service.name }}Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.{{ service.name.toCamelCase() }}Stub, undefined); + await client.initialize(); + assert(client.{{ service.name.toCamelCase() }}Stub); + }); + it('has close method', () => { + const client = new {{ service.name.toLowerCase() }}Module.{{ api.naming.version }}.{{ service.name }}Client({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.close(); + }); {%- for method in service.simpleMethods %} describe('{{ method.name.toCamelCase() }}', () => { it('invokes {{ method.name.toCamelCase() }} without error', done => { @@ -150,6 +166,8 @@ describe('{{ api.naming.version }}.{{ service.name }}Client', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request {{ util.initRequestWithHeaderParam(method) }} // Mock response @@ -172,6 +190,8 @@ describe('{{ api.naming.version }}.{{ service.name }}Client', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request {{ util.initRequestWithHeaderParam(method) }} // Mock response @@ -198,6 +218,8 @@ describe('{{ api.naming.version }}.{{ service.name }}Client', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request {{ util.initRequestWithHeaderParam(method) }} // Mock response @@ -223,6 +245,8 @@ describe('{{ api.naming.version }}.{{ service.name }}Client', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request {{ util.initRequestWithHeaderParam(method) }} // Mock response @@ -253,6 +277,8 @@ describe('{{ api.naming.version }}.{{ service.name }}Client', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request {{ util.initRequestWithHeaderParam(method) }} // Mock response @@ -274,6 +300,8 @@ describe('{{ api.naming.version }}.{{ service.name }}Client', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request {{ util.initRequestWithHeaderParam(method) }} // Mock response @@ -300,6 +328,8 @@ describe('{{ api.naming.version }}.{{ service.name }}Client', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request {{ util.initRequestWithHeaderParam(method) }} // Mock response @@ -319,6 +349,8 @@ describe('{{ api.naming.version }}.{{ service.name }}Client', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request {{ util.initRequestWithHeaderParam(method) }} // Mock response @@ -343,6 +375,8 @@ describe('{{ api.naming.version }}.{{ service.name }}Client', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request {{ util.initRequestWithHeaderParam(method) }} // Mock response @@ -365,6 +399,8 @@ describe('{{ api.naming.version }}.{{ service.name }}Client', () => { credentials: {client_email: 'bogus', private_key: 'bogus'}, projectId: 'bogus', }); + // Initialize client before mocking + client.initialize(); // Mock request {{ util.initRequestWithHeaderParam(method) }} // Mock response