diff --git a/src/v1/video_intelligence_service_client.ts b/src/v1/video_intelligence_service_client.ts index 48b8adde..0f0828ee 100644 --- a/src/v1/video_intelligence_service_client.ts +++ b/src/v1/video_intelligence_service_client.ts @@ -17,14 +17,7 @@ // ** All changes to this file may be overwritten. ** import * as gax from 'google-gax'; -import { - APICallback, - Callback, - CallOptions, - Descriptors, - ClientOptions, - LROperation, -} from 'google-gax'; +import {APICallback, Callback, CallOptions, Descriptors, ClientOptions, LROperation} from 'google-gax'; import * as path from 'path'; import * as protosTypes from '../../protos/protos'; @@ -41,9 +34,14 @@ export class VideoIntelligenceServiceClient { 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; operationsClient: gax.OperationsClient; - videoIntelligenceServiceStub: Promise<{[name: string]: Function}>; + videoIntelligenceServiceStub?: Promise<{[name: string]: Function}>; /** * Construct an instance of VideoIntelligenceServiceClient. @@ -67,22 +65,17 @@ export class VideoIntelligenceServiceClient { * app is running in an environment which supports * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, * your project ID will be detected automatically. - * @param {function} [options.promise] - Custom promise module to use instead - * of native Promises. * @param {string} [options.apiEndpoint] - The domain name of the * API remote host. */ constructor(opts?: ClientOptions) { // Ensure that options include the service address and port. - const staticMembers = this - .constructor as typeof VideoIntelligenceServiceClient; - const servicePath = - opts && opts.servicePath - ? opts.servicePath - : opts && opts.apiEndpoint - ? opts.apiEndpoint - : staticMembers.servicePath; + const staticMembers = this.constructor as typeof VideoIntelligenceServiceClient; + const servicePath = opts && opts.servicePath ? + opts.servicePath : + ((opts && opts.apiEndpoint) ? opts.apiEndpoint : + staticMembers.servicePath); const port = opts && opts.port ? opts.port : staticMembers.port; if (!opts) { @@ -92,33 +85,38 @@ export class VideoIntelligenceServiceClient { opts.port = opts.port || port; opts.clientConfig = opts.clientConfig || {}; - const isBrowser = typeof window !== 'undefined'; - if (isBrowser) { + const isBrowser = (typeof window !== 'undefined'); + if (isBrowser){ opts.fallback = true; } // If we are in browser, we are already using fallback because of the // "browser" field in package.json. // But if we were explicitly requested to use fallback, let's do it now. - const gaxModule = !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 VideoIntelligenceServiceClient).scopes; - const gaxGrpc = new gaxModule.GrpcClient(opts); + opts.scopes = (this.constructor as typeof VideoIntelligenceServiceClient).scopes; + 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}`, `gapic/${version}`]; + const clientHeader = [ + `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}`); @@ -127,74 +125,77 @@ export class VideoIntelligenceServiceClient { // For Node.js, pass the path to JSON proto file. // For browsers, pass the JSON content. - const nodejsProtoPath = path.join( - __dirname, - '..', - '..', - 'protos', - 'protos.json' - ); - const protos = gaxGrpc.loadProto( - opts.fallback ? require('../../protos/protos.json') : nodejsProtoPath + const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); + this._protos = this._gaxGrpc.loadProto( + opts.fallback ? + require("../../protos/protos.json") : + nodejsProtoPath ); // This API contains "long-running operations", which return a // an Operation object that allows for tracking of the operation, // rather than holding a request open. - const protoFilesRoot = opts.fallback - ? gaxModule.protobuf.Root.fromJSON(require('../../protos/protos.json')) - : gaxModule.protobuf.loadSync(nodejsProtoPath); - - this.operationsClient = gaxModule - .lro({ - auth: this.auth, - grpc: 'grpc' in gaxGrpc ? gaxGrpc.grpc : undefined, - }) - .operationsClient(opts); + const protoFilesRoot = opts.fallback? + this._gaxModule.protobuf.Root.fromJSON(require("../../protos/protos.json")) : + this._gaxModule.protobuf.loadSync(nodejsProtoPath); + + this.operationsClient = this._gaxModule.lro({ + auth: this.auth, + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + }).operationsClient(opts); const annotateVideoResponse = protoFilesRoot.lookup( - '.google.cloud.videointelligence.v1.AnnotateVideoResponse' - ) as gax.protobuf.Type; + '.google.cloud.videointelligence.v1.AnnotateVideoResponse') as gax.protobuf.Type; const annotateVideoMetadata = protoFilesRoot.lookup( - '.google.cloud.videointelligence.v1.AnnotateVideoProgress' - ) as gax.protobuf.Type; + '.google.cloud.videointelligence.v1.AnnotateVideoProgress') as gax.protobuf.Type; this._descriptors.longrunning = { - annotateVideo: new gaxModule.LongrunningDescriptor( + annotateVideo: new this._gaxModule.LongrunningDescriptor( this.operationsClient, annotateVideoResponse.decode.bind(annotateVideoResponse), - annotateVideoMetadata.decode.bind(annotateVideoMetadata) - ), + annotateVideoMetadata.decode.bind(annotateVideoMetadata)) }; // Put together the default options sent with requests. - const defaults = gaxGrpc.constructSettings( - 'google.cloud.videointelligence.v1.VideoIntelligenceService', - gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, - {'x-goog-api-client': clientHeader.join(' ')} - ); + this._defaults = this._gaxGrpc.constructSettings( + 'google.cloud.videointelligence.v1.VideoIntelligenceService', gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code // 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.videoIntelligenceServiceStub) { + return this.videoIntelligenceServiceStub; + } // Put together the "service stub" for // google.cloud.videointelligence.v1.VideoIntelligenceService. - this.videoIntelligenceServiceStub = gaxGrpc.createStub( - opts.fallback - ? (protos as protobuf.Root).lookupService( - 'google.cloud.videointelligence.v1.VideoIntelligenceService' - ) - : // tslint:disable-next-line no-any - (protos as any).google.cloud.videointelligence.v1 - .VideoIntelligenceService, - opts - ) as Promise<{[method: string]: Function}>; + this.videoIntelligenceServiceStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.cloud.videointelligence.v1.VideoIntelligenceService') : + // tslint:disable-next-line no-any + (this._protos as any).google.cloud.videointelligence.v1.VideoIntelligenceService, + 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. - const videoIntelligenceServiceStubMethods = ['annotateVideo']; + const videoIntelligenceServiceStubMethods = + ['annotateVideo']; for (const methodName of videoIntelligenceServiceStubMethods) { const innerCallPromise = this.videoIntelligenceServiceStub.then( @@ -204,17 +205,16 @@ export class VideoIntelligenceServiceClient { } return stub[methodName].apply(stub, args); }, - (err: Error | null | undefined) => () => { + (err: Error|null|undefined) => () => { 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] + this._descriptors.stream[methodName] || + this._descriptors.longrunning[methodName] ); this._innerApiCalls[methodName] = ( @@ -225,6 +225,8 @@ export class VideoIntelligenceServiceClient { return apiCall(argument, callOptions, callback); }; } + + return this.videoIntelligenceServiceStub; } /** @@ -254,7 +256,9 @@ export class VideoIntelligenceServiceClient { * in this service. */ static get scopes() { - return ['https://www.googleapis.com/auth/cloud-platform']; + return [ + 'https://www.googleapis.com/auth/cloud-platform' + ]; } getProjectId(): Promise; @@ -264,9 +268,8 @@ export class VideoIntelligenceServiceClient { * @param {function(Error, string)} callback - the callback to * be called with the current project Id. */ - getProjectId( - callback?: Callback - ): Promise | void { + getProjectId(callback?: Callback): + Promise|void { if (callback) { this.auth.getProjectId(callback); return; @@ -279,113 +282,87 @@ export class VideoIntelligenceServiceClient { // ------------------- annotateVideo( - request: protosTypes.google.cloud.videointelligence.v1.IAnnotateVideoRequest, - options?: gax.CallOptions - ): Promise< - [ - LROperation< - protosTypes.google.cloud.videointelligence.v1.IAnnotateVideoResponse, - protosTypes.google.cloud.videointelligence.v1.IAnnotateVideoProgress - >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined - ] - >; + request: protosTypes.google.cloud.videointelligence.v1.IAnnotateVideoRequest, + options?: gax.CallOptions): + Promise<[ + LROperation, + protosTypes.google.longrunning.IOperation|undefined, {}|undefined + ]>; annotateVideo( - request: protosTypes.google.cloud.videointelligence.v1.IAnnotateVideoRequest, - options: gax.CallOptions, - callback: Callback< - LROperation< - protosTypes.google.cloud.videointelligence.v1.IAnnotateVideoResponse, - protosTypes.google.cloud.videointelligence.v1.IAnnotateVideoProgress - >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined - > - ): void; - /** - * Performs asynchronous video annotation. Progress and results can be - * retrieved through the `google.longrunning.Operations` interface. - * `Operation.metadata` contains `AnnotateVideoProgress` (progress). - * `Operation.response` contains `AnnotateVideoResponse` (results). - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.inputUri - * Input video location. Currently, only - * [Google Cloud Storage](https://cloud.google.com/storage/) URIs are - * supported, which must be specified in the following format: - * `gs://bucket-id/object-id` (other URI formats return - * [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For more information, see - * [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). - * A video URI may include wildcards in `object-id`, and thus identify - * multiple videos. Supported wildcards: '*' to match 0 or more characters; - * '?' to match 1 character. If unset, the input video should be embedded - * in the request as `input_content`. If set, `input_content` should be unset. - * @param {Buffer} request.inputContent - * The video data bytes. - * If unset, the input video(s) should be specified via `input_uri`. - * If set, `input_uri` should be unset. - * @param {number[]} request.features - * Required. Requested video annotation features. - * @param {google.cloud.videointelligence.v1.VideoContext} request.videoContext - * Additional video context and/or feature-specific parameters. - * @param {string} [request.outputUri] - * Optional. Location where the output (in JSON format) should be stored. - * Currently, only [Google Cloud Storage](https://cloud.google.com/storage/) - * URIs are supported, which must be specified in the following format: - * `gs://bucket-id/object-id` (other URI formats return - * [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For more information, see - * [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). - * @param {string} [request.locationId] - * Optional. Cloud region where annotation should take place. Supported cloud - * regions: `us-east1`, `us-west1`, `europe-west1`, `asia-east1`. If no region - * is specified, a region will be determined based on video file location. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [Operation]{@link google.longrunning.Operation}. - * The promise has a method named "cancel" which cancels the ongoing API call. - */ + request: protosTypes.google.cloud.videointelligence.v1.IAnnotateVideoRequest, + options: gax.CallOptions, + callback: Callback< + LROperation, + protosTypes.google.longrunning.IOperation|undefined, + {}|undefined>): void; +/** + * Performs asynchronous video annotation. Progress and results can be + * retrieved through the `google.longrunning.Operations` interface. + * `Operation.metadata` contains `AnnotateVideoProgress` (progress). + * `Operation.response` contains `AnnotateVideoResponse` (results). + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.inputUri + * Input video location. Currently, only + * [Google Cloud Storage](https://cloud.google.com/storage/) URIs are + * supported, which must be specified in the following format: + * `gs://bucket-id/object-id` (other URI formats return + * {@link google.rpc.Code.INVALID_ARGUMENT|google.rpc.Code.INVALID_ARGUMENT}). For more information, see + * [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). + * A video URI may include wildcards in `object-id`, and thus identify + * multiple videos. Supported wildcards: '*' to match 0 or more characters; + * '?' to match 1 character. If unset, the input video should be embedded + * in the request as `input_content`. If set, `input_content` should be unset. + * @param {Buffer} request.inputContent + * The video data bytes. + * If unset, the input video(s) should be specified via `input_uri`. + * If set, `input_uri` should be unset. + * @param {number[]} request.features + * Required. Requested video annotation features. + * @param {google.cloud.videointelligence.v1.VideoContext} request.videoContext + * Additional video context and/or feature-specific parameters. + * @param {string} [request.outputUri] + * Optional. Location where the output (in JSON format) should be stored. + * Currently, only [Google Cloud Storage](https://cloud.google.com/storage/) + * URIs are supported, which must be specified in the following format: + * `gs://bucket-id/object-id` (other URI formats return + * {@link google.rpc.Code.INVALID_ARGUMENT|google.rpc.Code.INVALID_ARGUMENT}). For more information, see + * [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). + * @param {string} [request.locationId] + * Optional. Cloud region where annotation should take place. Supported cloud + * regions: `us-east1`, `us-west1`, `europe-west1`, `asia-east1`. If no region + * is specified, a region will be determined based on video file location. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing [Operation]{@link google.longrunning.Operation}. + * The promise has a method named "cancel" which cancels the ongoing API call. + */ annotateVideo( - request: protosTypes.google.cloud.videointelligence.v1.IAnnotateVideoRequest, - optionsOrCallback?: - | gax.CallOptions - | Callback< - LROperation< - protosTypes.google.cloud.videointelligence.v1.IAnnotateVideoResponse, - protosTypes.google.cloud.videointelligence.v1.IAnnotateVideoProgress - >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined - >, - callback?: Callback< - LROperation< - protosTypes.google.cloud.videointelligence.v1.IAnnotateVideoResponse, - protosTypes.google.cloud.videointelligence.v1.IAnnotateVideoProgress - >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined - > - ): Promise< - [ - LROperation< - protosTypes.google.cloud.videointelligence.v1.IAnnotateVideoResponse, - protosTypes.google.cloud.videointelligence.v1.IAnnotateVideoProgress - >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined - ] - > | void { + request: protosTypes.google.cloud.videointelligence.v1.IAnnotateVideoRequest, + optionsOrCallback?: gax.CallOptions|Callback< + LROperation, + protosTypes.google.longrunning.IOperation|undefined, {}|undefined>, + callback?: Callback< + LROperation, + protosTypes.google.longrunning.IOperation|undefined, + {}|undefined>): + Promise<[ + LROperation, + protosTypes.google.longrunning.IOperation|undefined, {}|undefined + ]>|void { request = request || {}; let options: gax.CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as gax.CallOptions; } options = options || {}; + this.initialize(); return this._innerApiCalls.annotateVideo(request, options, callback); } @@ -395,8 +372,9 @@ export class VideoIntelligenceServiceClient { * The client will no longer be usable and all future behavior is undefined. */ close(): Promise { + this.initialize(); if (!this._terminated) { - return this.videoIntelligenceServiceStub.then(stub => { + return this.videoIntelligenceServiceStub!.then(stub => { this._terminated = true; stub.close(); }); diff --git a/src/v1beta2/video_intelligence_service_client.ts b/src/v1beta2/video_intelligence_service_client.ts index f28cf0ae..0dd0d120 100644 --- a/src/v1beta2/video_intelligence_service_client.ts +++ b/src/v1beta2/video_intelligence_service_client.ts @@ -17,14 +17,7 @@ // ** All changes to this file may be overwritten. ** import * as gax from 'google-gax'; -import { - APICallback, - Callback, - CallOptions, - Descriptors, - ClientOptions, - LROperation, -} from 'google-gax'; +import {APICallback, Callback, CallOptions, Descriptors, ClientOptions, LROperation} from 'google-gax'; import * as path from 'path'; import * as protosTypes from '../../protos/protos'; @@ -41,9 +34,14 @@ export class VideoIntelligenceServiceClient { 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; operationsClient: gax.OperationsClient; - videoIntelligenceServiceStub: Promise<{[name: string]: Function}>; + videoIntelligenceServiceStub?: Promise<{[name: string]: Function}>; /** * Construct an instance of VideoIntelligenceServiceClient. @@ -67,22 +65,17 @@ export class VideoIntelligenceServiceClient { * app is running in an environment which supports * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, * your project ID will be detected automatically. - * @param {function} [options.promise] - Custom promise module to use instead - * of native Promises. * @param {string} [options.apiEndpoint] - The domain name of the * API remote host. */ constructor(opts?: ClientOptions) { // Ensure that options include the service address and port. - const staticMembers = this - .constructor as typeof VideoIntelligenceServiceClient; - const servicePath = - opts && opts.servicePath - ? opts.servicePath - : opts && opts.apiEndpoint - ? opts.apiEndpoint - : staticMembers.servicePath; + const staticMembers = this.constructor as typeof VideoIntelligenceServiceClient; + const servicePath = opts && opts.servicePath ? + opts.servicePath : + ((opts && opts.apiEndpoint) ? opts.apiEndpoint : + staticMembers.servicePath); const port = opts && opts.port ? opts.port : staticMembers.port; if (!opts) { @@ -92,33 +85,38 @@ export class VideoIntelligenceServiceClient { opts.port = opts.port || port; opts.clientConfig = opts.clientConfig || {}; - const isBrowser = typeof window !== 'undefined'; - if (isBrowser) { + const isBrowser = (typeof window !== 'undefined'); + if (isBrowser){ opts.fallback = true; } // If we are in browser, we are already using fallback because of the // "browser" field in package.json. // But if we were explicitly requested to use fallback, let's do it now. - const gaxModule = !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 VideoIntelligenceServiceClient).scopes; - const gaxGrpc = new gaxModule.GrpcClient(opts); + opts.scopes = (this.constructor as typeof VideoIntelligenceServiceClient).scopes; + 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}`, `gapic/${version}`]; + const clientHeader = [ + `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}`); @@ -127,74 +125,77 @@ export class VideoIntelligenceServiceClient { // For Node.js, pass the path to JSON proto file. // For browsers, pass the JSON content. - const nodejsProtoPath = path.join( - __dirname, - '..', - '..', - 'protos', - 'protos.json' - ); - const protos = gaxGrpc.loadProto( - opts.fallback ? require('../../protos/protos.json') : nodejsProtoPath + const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); + this._protos = this._gaxGrpc.loadProto( + opts.fallback ? + require("../../protos/protos.json") : + nodejsProtoPath ); // This API contains "long-running operations", which return a // an Operation object that allows for tracking of the operation, // rather than holding a request open. - const protoFilesRoot = opts.fallback - ? gaxModule.protobuf.Root.fromJSON(require('../../protos/protos.json')) - : gaxModule.protobuf.loadSync(nodejsProtoPath); - - this.operationsClient = gaxModule - .lro({ - auth: this.auth, - grpc: 'grpc' in gaxGrpc ? gaxGrpc.grpc : undefined, - }) - .operationsClient(opts); + const protoFilesRoot = opts.fallback? + this._gaxModule.protobuf.Root.fromJSON(require("../../protos/protos.json")) : + this._gaxModule.protobuf.loadSync(nodejsProtoPath); + + this.operationsClient = this._gaxModule.lro({ + auth: this.auth, + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + }).operationsClient(opts); const annotateVideoResponse = protoFilesRoot.lookup( - '.google.cloud.videointelligence.v1beta2.AnnotateVideoResponse' - ) as gax.protobuf.Type; + '.google.cloud.videointelligence.v1beta2.AnnotateVideoResponse') as gax.protobuf.Type; const annotateVideoMetadata = protoFilesRoot.lookup( - '.google.cloud.videointelligence.v1beta2.AnnotateVideoProgress' - ) as gax.protobuf.Type; + '.google.cloud.videointelligence.v1beta2.AnnotateVideoProgress') as gax.protobuf.Type; this._descriptors.longrunning = { - annotateVideo: new gaxModule.LongrunningDescriptor( + annotateVideo: new this._gaxModule.LongrunningDescriptor( this.operationsClient, annotateVideoResponse.decode.bind(annotateVideoResponse), - annotateVideoMetadata.decode.bind(annotateVideoMetadata) - ), + annotateVideoMetadata.decode.bind(annotateVideoMetadata)) }; // Put together the default options sent with requests. - const defaults = gaxGrpc.constructSettings( - 'google.cloud.videointelligence.v1beta2.VideoIntelligenceService', - gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, - {'x-goog-api-client': clientHeader.join(' ')} - ); + this._defaults = this._gaxGrpc.constructSettings( + 'google.cloud.videointelligence.v1beta2.VideoIntelligenceService', gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code // 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.videoIntelligenceServiceStub) { + return this.videoIntelligenceServiceStub; + } // Put together the "service stub" for // google.cloud.videointelligence.v1beta2.VideoIntelligenceService. - this.videoIntelligenceServiceStub = gaxGrpc.createStub( - opts.fallback - ? (protos as protobuf.Root).lookupService( - 'google.cloud.videointelligence.v1beta2.VideoIntelligenceService' - ) - : // tslint:disable-next-line no-any - (protos as any).google.cloud.videointelligence.v1beta2 - .VideoIntelligenceService, - opts - ) as Promise<{[method: string]: Function}>; + this.videoIntelligenceServiceStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.cloud.videointelligence.v1beta2.VideoIntelligenceService') : + // tslint:disable-next-line no-any + (this._protos as any).google.cloud.videointelligence.v1beta2.VideoIntelligenceService, + 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. - const videoIntelligenceServiceStubMethods = ['annotateVideo']; + const videoIntelligenceServiceStubMethods = + ['annotateVideo']; for (const methodName of videoIntelligenceServiceStubMethods) { const innerCallPromise = this.videoIntelligenceServiceStub.then( @@ -204,17 +205,16 @@ export class VideoIntelligenceServiceClient { } return stub[methodName].apply(stub, args); }, - (err: Error | null | undefined) => () => { + (err: Error|null|undefined) => () => { 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] + this._descriptors.stream[methodName] || + this._descriptors.longrunning[methodName] ); this._innerApiCalls[methodName] = ( @@ -225,6 +225,8 @@ export class VideoIntelligenceServiceClient { return apiCall(argument, callOptions, callback); }; } + + return this.videoIntelligenceServiceStub; } /** @@ -254,7 +256,9 @@ export class VideoIntelligenceServiceClient { * in this service. */ static get scopes() { - return ['https://www.googleapis.com/auth/cloud-platform']; + return [ + 'https://www.googleapis.com/auth/cloud-platform' + ]; } getProjectId(): Promise; @@ -264,9 +268,8 @@ export class VideoIntelligenceServiceClient { * @param {function(Error, string)} callback - the callback to * be called with the current project Id. */ - getProjectId( - callback?: Callback - ): Promise | void { + getProjectId(callback?: Callback): + Promise|void { if (callback) { this.auth.getProjectId(callback); return; @@ -279,113 +282,87 @@ export class VideoIntelligenceServiceClient { // ------------------- annotateVideo( - request: protosTypes.google.cloud.videointelligence.v1beta2.IAnnotateVideoRequest, - options?: gax.CallOptions - ): Promise< - [ - LROperation< - protosTypes.google.cloud.videointelligence.v1beta2.IAnnotateVideoResponse, - protosTypes.google.cloud.videointelligence.v1beta2.IAnnotateVideoProgress - >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined - ] - >; + request: protosTypes.google.cloud.videointelligence.v1beta2.IAnnotateVideoRequest, + options?: gax.CallOptions): + Promise<[ + LROperation, + protosTypes.google.longrunning.IOperation|undefined, {}|undefined + ]>; annotateVideo( - request: protosTypes.google.cloud.videointelligence.v1beta2.IAnnotateVideoRequest, - options: gax.CallOptions, - callback: Callback< - LROperation< - protosTypes.google.cloud.videointelligence.v1beta2.IAnnotateVideoResponse, - protosTypes.google.cloud.videointelligence.v1beta2.IAnnotateVideoProgress - >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined - > - ): void; - /** - * Performs asynchronous video annotation. Progress and results can be - * retrieved through the `google.longrunning.Operations` interface. - * `Operation.metadata` contains `AnnotateVideoProgress` (progress). - * `Operation.response` contains `AnnotateVideoResponse` (results). - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.inputUri - * Input video location. Currently, only - * [Google Cloud Storage](https://cloud.google.com/storage/) URIs are - * supported, which must be specified in the following format: - * `gs://bucket-id/object-id` (other URI formats return - * [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For - * more information, see [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). A video - * URI may include wildcards in `object-id`, and thus identify multiple - * videos. Supported wildcards: '*' to match 0 or more characters; - * '?' to match 1 character. If unset, the input video should be embedded - * in the request as `input_content`. If set, `input_content` should be unset. - * @param {Buffer} request.inputContent - * The video data bytes. - * If unset, the input video(s) should be specified via `input_uri`. - * If set, `input_uri` should be unset. - * @param {number[]} request.features - * Required. Requested video annotation features. - * @param {google.cloud.videointelligence.v1beta2.VideoContext} request.videoContext - * Additional video context and/or feature-specific parameters. - * @param {string} [request.outputUri] - * Optional. Location where the output (in JSON format) should be stored. - * Currently, only [Google Cloud Storage](https://cloud.google.com/storage/) - * URIs are supported, which must be specified in the following format: - * `gs://bucket-id/object-id` (other URI formats return - * [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For - * more information, see [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). - * @param {string} [request.locationId] - * Optional. Cloud region where annotation should take place. Supported cloud - * regions: `us-east1`, `us-west1`, `europe-west1`, `asia-east1`. If no region - * is specified, a region will be determined based on video file location. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [Operation]{@link google.longrunning.Operation}. - * The promise has a method named "cancel" which cancels the ongoing API call. - */ + request: protosTypes.google.cloud.videointelligence.v1beta2.IAnnotateVideoRequest, + options: gax.CallOptions, + callback: Callback< + LROperation, + protosTypes.google.longrunning.IOperation|undefined, + {}|undefined>): void; +/** + * Performs asynchronous video annotation. Progress and results can be + * retrieved through the `google.longrunning.Operations` interface. + * `Operation.metadata` contains `AnnotateVideoProgress` (progress). + * `Operation.response` contains `AnnotateVideoResponse` (results). + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.inputUri + * Input video location. Currently, only + * [Google Cloud Storage](https://cloud.google.com/storage/) URIs are + * supported, which must be specified in the following format: + * `gs://bucket-id/object-id` (other URI formats return + * {@link google.rpc.Code.INVALID_ARGUMENT|google.rpc.Code.INVALID_ARGUMENT}). For + * more information, see [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). A video + * URI may include wildcards in `object-id`, and thus identify multiple + * videos. Supported wildcards: '*' to match 0 or more characters; + * '?' to match 1 character. If unset, the input video should be embedded + * in the request as `input_content`. If set, `input_content` should be unset. + * @param {Buffer} request.inputContent + * The video data bytes. + * If unset, the input video(s) should be specified via `input_uri`. + * If set, `input_uri` should be unset. + * @param {number[]} request.features + * Required. Requested video annotation features. + * @param {google.cloud.videointelligence.v1beta2.VideoContext} request.videoContext + * Additional video context and/or feature-specific parameters. + * @param {string} [request.outputUri] + * Optional. Location where the output (in JSON format) should be stored. + * Currently, only [Google Cloud Storage](https://cloud.google.com/storage/) + * URIs are supported, which must be specified in the following format: + * `gs://bucket-id/object-id` (other URI formats return + * {@link google.rpc.Code.INVALID_ARGUMENT|google.rpc.Code.INVALID_ARGUMENT}). For + * more information, see [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). + * @param {string} [request.locationId] + * Optional. Cloud region where annotation should take place. Supported cloud + * regions: `us-east1`, `us-west1`, `europe-west1`, `asia-east1`. If no region + * is specified, a region will be determined based on video file location. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing [Operation]{@link google.longrunning.Operation}. + * The promise has a method named "cancel" which cancels the ongoing API call. + */ annotateVideo( - request: protosTypes.google.cloud.videointelligence.v1beta2.IAnnotateVideoRequest, - optionsOrCallback?: - | gax.CallOptions - | Callback< - LROperation< - protosTypes.google.cloud.videointelligence.v1beta2.IAnnotateVideoResponse, - protosTypes.google.cloud.videointelligence.v1beta2.IAnnotateVideoProgress - >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined - >, - callback?: Callback< - LROperation< - protosTypes.google.cloud.videointelligence.v1beta2.IAnnotateVideoResponse, - protosTypes.google.cloud.videointelligence.v1beta2.IAnnotateVideoProgress - >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined - > - ): Promise< - [ - LROperation< - protosTypes.google.cloud.videointelligence.v1beta2.IAnnotateVideoResponse, - protosTypes.google.cloud.videointelligence.v1beta2.IAnnotateVideoProgress - >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined - ] - > | void { + request: protosTypes.google.cloud.videointelligence.v1beta2.IAnnotateVideoRequest, + optionsOrCallback?: gax.CallOptions|Callback< + LROperation, + protosTypes.google.longrunning.IOperation|undefined, {}|undefined>, + callback?: Callback< + LROperation, + protosTypes.google.longrunning.IOperation|undefined, + {}|undefined>): + Promise<[ + LROperation, + protosTypes.google.longrunning.IOperation|undefined, {}|undefined + ]>|void { request = request || {}; let options: gax.CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as gax.CallOptions; } options = options || {}; + this.initialize(); return this._innerApiCalls.annotateVideo(request, options, callback); } @@ -395,8 +372,9 @@ export class VideoIntelligenceServiceClient { * The client will no longer be usable and all future behavior is undefined. */ close(): Promise { + this.initialize(); if (!this._terminated) { - return this.videoIntelligenceServiceStub.then(stub => { + return this.videoIntelligenceServiceStub!.then(stub => { this._terminated = true; stub.close(); }); diff --git a/src/v1p1beta1/video_intelligence_service_client.ts b/src/v1p1beta1/video_intelligence_service_client.ts index cee76bc7..3919a44f 100644 --- a/src/v1p1beta1/video_intelligence_service_client.ts +++ b/src/v1p1beta1/video_intelligence_service_client.ts @@ -17,14 +17,7 @@ // ** All changes to this file may be overwritten. ** import * as gax from 'google-gax'; -import { - APICallback, - Callback, - CallOptions, - Descriptors, - ClientOptions, - LROperation, -} from 'google-gax'; +import {APICallback, Callback, CallOptions, Descriptors, ClientOptions, LROperation} from 'google-gax'; import * as path from 'path'; import * as protosTypes from '../../protos/protos'; @@ -41,9 +34,14 @@ export class VideoIntelligenceServiceClient { 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; operationsClient: gax.OperationsClient; - videoIntelligenceServiceStub: Promise<{[name: string]: Function}>; + videoIntelligenceServiceStub?: Promise<{[name: string]: Function}>; /** * Construct an instance of VideoIntelligenceServiceClient. @@ -67,22 +65,17 @@ export class VideoIntelligenceServiceClient { * app is running in an environment which supports * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, * your project ID will be detected automatically. - * @param {function} [options.promise] - Custom promise module to use instead - * of native Promises. * @param {string} [options.apiEndpoint] - The domain name of the * API remote host. */ constructor(opts?: ClientOptions) { // Ensure that options include the service address and port. - const staticMembers = this - .constructor as typeof VideoIntelligenceServiceClient; - const servicePath = - opts && opts.servicePath - ? opts.servicePath - : opts && opts.apiEndpoint - ? opts.apiEndpoint - : staticMembers.servicePath; + const staticMembers = this.constructor as typeof VideoIntelligenceServiceClient; + const servicePath = opts && opts.servicePath ? + opts.servicePath : + ((opts && opts.apiEndpoint) ? opts.apiEndpoint : + staticMembers.servicePath); const port = opts && opts.port ? opts.port : staticMembers.port; if (!opts) { @@ -92,33 +85,38 @@ export class VideoIntelligenceServiceClient { opts.port = opts.port || port; opts.clientConfig = opts.clientConfig || {}; - const isBrowser = typeof window !== 'undefined'; - if (isBrowser) { + const isBrowser = (typeof window !== 'undefined'); + if (isBrowser){ opts.fallback = true; } // If we are in browser, we are already using fallback because of the // "browser" field in package.json. // But if we were explicitly requested to use fallback, let's do it now. - const gaxModule = !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 VideoIntelligenceServiceClient).scopes; - const gaxGrpc = new gaxModule.GrpcClient(opts); + opts.scopes = (this.constructor as typeof VideoIntelligenceServiceClient).scopes; + 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}`, `gapic/${version}`]; + const clientHeader = [ + `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}`); @@ -127,74 +125,77 @@ export class VideoIntelligenceServiceClient { // For Node.js, pass the path to JSON proto file. // For browsers, pass the JSON content. - const nodejsProtoPath = path.join( - __dirname, - '..', - '..', - 'protos', - 'protos.json' - ); - const protos = gaxGrpc.loadProto( - opts.fallback ? require('../../protos/protos.json') : nodejsProtoPath + const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); + this._protos = this._gaxGrpc.loadProto( + opts.fallback ? + require("../../protos/protos.json") : + nodejsProtoPath ); // This API contains "long-running operations", which return a // an Operation object that allows for tracking of the operation, // rather than holding a request open. - const protoFilesRoot = opts.fallback - ? gaxModule.protobuf.Root.fromJSON(require('../../protos/protos.json')) - : gaxModule.protobuf.loadSync(nodejsProtoPath); - - this.operationsClient = gaxModule - .lro({ - auth: this.auth, - grpc: 'grpc' in gaxGrpc ? gaxGrpc.grpc : undefined, - }) - .operationsClient(opts); + const protoFilesRoot = opts.fallback? + this._gaxModule.protobuf.Root.fromJSON(require("../../protos/protos.json")) : + this._gaxModule.protobuf.loadSync(nodejsProtoPath); + + this.operationsClient = this._gaxModule.lro({ + auth: this.auth, + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + }).operationsClient(opts); const annotateVideoResponse = protoFilesRoot.lookup( - '.google.cloud.videointelligence.v1p1beta1.AnnotateVideoResponse' - ) as gax.protobuf.Type; + '.google.cloud.videointelligence.v1p1beta1.AnnotateVideoResponse') as gax.protobuf.Type; const annotateVideoMetadata = protoFilesRoot.lookup( - '.google.cloud.videointelligence.v1p1beta1.AnnotateVideoProgress' - ) as gax.protobuf.Type; + '.google.cloud.videointelligence.v1p1beta1.AnnotateVideoProgress') as gax.protobuf.Type; this._descriptors.longrunning = { - annotateVideo: new gaxModule.LongrunningDescriptor( + annotateVideo: new this._gaxModule.LongrunningDescriptor( this.operationsClient, annotateVideoResponse.decode.bind(annotateVideoResponse), - annotateVideoMetadata.decode.bind(annotateVideoMetadata) - ), + annotateVideoMetadata.decode.bind(annotateVideoMetadata)) }; // Put together the default options sent with requests. - const defaults = gaxGrpc.constructSettings( - 'google.cloud.videointelligence.v1p1beta1.VideoIntelligenceService', - gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, - {'x-goog-api-client': clientHeader.join(' ')} - ); + this._defaults = this._gaxGrpc.constructSettings( + 'google.cloud.videointelligence.v1p1beta1.VideoIntelligenceService', gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code // 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.videoIntelligenceServiceStub) { + return this.videoIntelligenceServiceStub; + } // Put together the "service stub" for // google.cloud.videointelligence.v1p1beta1.VideoIntelligenceService. - this.videoIntelligenceServiceStub = gaxGrpc.createStub( - opts.fallback - ? (protos as protobuf.Root).lookupService( - 'google.cloud.videointelligence.v1p1beta1.VideoIntelligenceService' - ) - : // tslint:disable-next-line no-any - (protos as any).google.cloud.videointelligence.v1p1beta1 - .VideoIntelligenceService, - opts - ) as Promise<{[method: string]: Function}>; + this.videoIntelligenceServiceStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.cloud.videointelligence.v1p1beta1.VideoIntelligenceService') : + // tslint:disable-next-line no-any + (this._protos as any).google.cloud.videointelligence.v1p1beta1.VideoIntelligenceService, + 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. - const videoIntelligenceServiceStubMethods = ['annotateVideo']; + const videoIntelligenceServiceStubMethods = + ['annotateVideo']; for (const methodName of videoIntelligenceServiceStubMethods) { const innerCallPromise = this.videoIntelligenceServiceStub.then( @@ -204,17 +205,16 @@ export class VideoIntelligenceServiceClient { } return stub[methodName].apply(stub, args); }, - (err: Error | null | undefined) => () => { + (err: Error|null|undefined) => () => { 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] + this._descriptors.stream[methodName] || + this._descriptors.longrunning[methodName] ); this._innerApiCalls[methodName] = ( @@ -225,6 +225,8 @@ export class VideoIntelligenceServiceClient { return apiCall(argument, callOptions, callback); }; } + + return this.videoIntelligenceServiceStub; } /** @@ -254,7 +256,9 @@ export class VideoIntelligenceServiceClient { * in this service. */ static get scopes() { - return ['https://www.googleapis.com/auth/cloud-platform']; + return [ + 'https://www.googleapis.com/auth/cloud-platform' + ]; } getProjectId(): Promise; @@ -264,9 +268,8 @@ export class VideoIntelligenceServiceClient { * @param {function(Error, string)} callback - the callback to * be called with the current project Id. */ - getProjectId( - callback?: Callback - ): Promise | void { + getProjectId(callback?: Callback): + Promise|void { if (callback) { this.auth.getProjectId(callback); return; @@ -279,113 +282,87 @@ export class VideoIntelligenceServiceClient { // ------------------- annotateVideo( - request: protosTypes.google.cloud.videointelligence.v1p1beta1.IAnnotateVideoRequest, - options?: gax.CallOptions - ): Promise< - [ - LROperation< - protosTypes.google.cloud.videointelligence.v1p1beta1.IAnnotateVideoResponse, - protosTypes.google.cloud.videointelligence.v1p1beta1.IAnnotateVideoProgress - >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined - ] - >; + request: protosTypes.google.cloud.videointelligence.v1p1beta1.IAnnotateVideoRequest, + options?: gax.CallOptions): + Promise<[ + LROperation, + protosTypes.google.longrunning.IOperation|undefined, {}|undefined + ]>; annotateVideo( - request: protosTypes.google.cloud.videointelligence.v1p1beta1.IAnnotateVideoRequest, - options: gax.CallOptions, - callback: Callback< - LROperation< - protosTypes.google.cloud.videointelligence.v1p1beta1.IAnnotateVideoResponse, - protosTypes.google.cloud.videointelligence.v1p1beta1.IAnnotateVideoProgress - >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined - > - ): void; - /** - * Performs asynchronous video annotation. Progress and results can be - * retrieved through the `google.longrunning.Operations` interface. - * `Operation.metadata` contains `AnnotateVideoProgress` (progress). - * `Operation.response` contains `AnnotateVideoResponse` (results). - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.inputUri - * Input video location. Currently, only - * [Google Cloud Storage](https://cloud.google.com/storage/) URIs are - * supported, which must be specified in the following format: - * `gs://bucket-id/object-id` (other URI formats return - * [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For more information, see - * [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). - * A video URI may include wildcards in `object-id`, and thus identify - * multiple videos. Supported wildcards: '*' to match 0 or more characters; - * '?' to match 1 character. If unset, the input video should be embedded - * in the request as `input_content`. If set, `input_content` should be unset. - * @param {Buffer} request.inputContent - * The video data bytes. - * If unset, the input video(s) should be specified via `input_uri`. - * If set, `input_uri` should be unset. - * @param {number[]} request.features - * Required. Requested video annotation features. - * @param {google.cloud.videointelligence.v1p1beta1.VideoContext} request.videoContext - * Additional video context and/or feature-specific parameters. - * @param {string} [request.outputUri] - * Optional. Location where the output (in JSON format) should be stored. - * Currently, only [Google Cloud Storage](https://cloud.google.com/storage/) - * URIs are supported, which must be specified in the following format: - * `gs://bucket-id/object-id` (other URI formats return - * [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For more information, see - * [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). - * @param {string} [request.locationId] - * Optional. Cloud region where annotation should take place. Supported cloud - * regions: `us-east1`, `us-west1`, `europe-west1`, `asia-east1`. If no region - * is specified, a region will be determined based on video file location. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [Operation]{@link google.longrunning.Operation}. - * The promise has a method named "cancel" which cancels the ongoing API call. - */ + request: protosTypes.google.cloud.videointelligence.v1p1beta1.IAnnotateVideoRequest, + options: gax.CallOptions, + callback: Callback< + LROperation, + protosTypes.google.longrunning.IOperation|undefined, + {}|undefined>): void; +/** + * Performs asynchronous video annotation. Progress and results can be + * retrieved through the `google.longrunning.Operations` interface. + * `Operation.metadata` contains `AnnotateVideoProgress` (progress). + * `Operation.response` contains `AnnotateVideoResponse` (results). + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.inputUri + * Input video location. Currently, only + * [Google Cloud Storage](https://cloud.google.com/storage/) URIs are + * supported, which must be specified in the following format: + * `gs://bucket-id/object-id` (other URI formats return + * {@link google.rpc.Code.INVALID_ARGUMENT|google.rpc.Code.INVALID_ARGUMENT}). For more information, see + * [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). + * A video URI may include wildcards in `object-id`, and thus identify + * multiple videos. Supported wildcards: '*' to match 0 or more characters; + * '?' to match 1 character. If unset, the input video should be embedded + * in the request as `input_content`. If set, `input_content` should be unset. + * @param {Buffer} request.inputContent + * The video data bytes. + * If unset, the input video(s) should be specified via `input_uri`. + * If set, `input_uri` should be unset. + * @param {number[]} request.features + * Required. Requested video annotation features. + * @param {google.cloud.videointelligence.v1p1beta1.VideoContext} request.videoContext + * Additional video context and/or feature-specific parameters. + * @param {string} [request.outputUri] + * Optional. Location where the output (in JSON format) should be stored. + * Currently, only [Google Cloud Storage](https://cloud.google.com/storage/) + * URIs are supported, which must be specified in the following format: + * `gs://bucket-id/object-id` (other URI formats return + * {@link google.rpc.Code.INVALID_ARGUMENT|google.rpc.Code.INVALID_ARGUMENT}). For more information, see + * [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). + * @param {string} [request.locationId] + * Optional. Cloud region where annotation should take place. Supported cloud + * regions: `us-east1`, `us-west1`, `europe-west1`, `asia-east1`. If no region + * is specified, a region will be determined based on video file location. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing [Operation]{@link google.longrunning.Operation}. + * The promise has a method named "cancel" which cancels the ongoing API call. + */ annotateVideo( - request: protosTypes.google.cloud.videointelligence.v1p1beta1.IAnnotateVideoRequest, - optionsOrCallback?: - | gax.CallOptions - | Callback< - LROperation< - protosTypes.google.cloud.videointelligence.v1p1beta1.IAnnotateVideoResponse, - protosTypes.google.cloud.videointelligence.v1p1beta1.IAnnotateVideoProgress - >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined - >, - callback?: Callback< - LROperation< - protosTypes.google.cloud.videointelligence.v1p1beta1.IAnnotateVideoResponse, - protosTypes.google.cloud.videointelligence.v1p1beta1.IAnnotateVideoProgress - >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined - > - ): Promise< - [ - LROperation< - protosTypes.google.cloud.videointelligence.v1p1beta1.IAnnotateVideoResponse, - protosTypes.google.cloud.videointelligence.v1p1beta1.IAnnotateVideoProgress - >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined - ] - > | void { + request: protosTypes.google.cloud.videointelligence.v1p1beta1.IAnnotateVideoRequest, + optionsOrCallback?: gax.CallOptions|Callback< + LROperation, + protosTypes.google.longrunning.IOperation|undefined, {}|undefined>, + callback?: Callback< + LROperation, + protosTypes.google.longrunning.IOperation|undefined, + {}|undefined>): + Promise<[ + LROperation, + protosTypes.google.longrunning.IOperation|undefined, {}|undefined + ]>|void { request = request || {}; let options: gax.CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as gax.CallOptions; } options = options || {}; + this.initialize(); return this._innerApiCalls.annotateVideo(request, options, callback); } @@ -395,8 +372,9 @@ export class VideoIntelligenceServiceClient { * The client will no longer be usable and all future behavior is undefined. */ close(): Promise { + this.initialize(); if (!this._terminated) { - return this.videoIntelligenceServiceStub.then(stub => { + return this.videoIntelligenceServiceStub!.then(stub => { this._terminated = true; stub.close(); }); diff --git a/src/v1p2beta1/video_intelligence_service_client.ts b/src/v1p2beta1/video_intelligence_service_client.ts index f0c9dce7..50619ff2 100644 --- a/src/v1p2beta1/video_intelligence_service_client.ts +++ b/src/v1p2beta1/video_intelligence_service_client.ts @@ -17,14 +17,7 @@ // ** All changes to this file may be overwritten. ** import * as gax from 'google-gax'; -import { - APICallback, - Callback, - CallOptions, - Descriptors, - ClientOptions, - LROperation, -} from 'google-gax'; +import {APICallback, Callback, CallOptions, Descriptors, ClientOptions, LROperation} from 'google-gax'; import * as path from 'path'; import * as protosTypes from '../../protos/protos'; @@ -41,9 +34,14 @@ export class VideoIntelligenceServiceClient { 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; operationsClient: gax.OperationsClient; - videoIntelligenceServiceStub: Promise<{[name: string]: Function}>; + videoIntelligenceServiceStub?: Promise<{[name: string]: Function}>; /** * Construct an instance of VideoIntelligenceServiceClient. @@ -67,22 +65,17 @@ export class VideoIntelligenceServiceClient { * app is running in an environment which supports * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, * your project ID will be detected automatically. - * @param {function} [options.promise] - Custom promise module to use instead - * of native Promises. * @param {string} [options.apiEndpoint] - The domain name of the * API remote host. */ constructor(opts?: ClientOptions) { // Ensure that options include the service address and port. - const staticMembers = this - .constructor as typeof VideoIntelligenceServiceClient; - const servicePath = - opts && opts.servicePath - ? opts.servicePath - : opts && opts.apiEndpoint - ? opts.apiEndpoint - : staticMembers.servicePath; + const staticMembers = this.constructor as typeof VideoIntelligenceServiceClient; + const servicePath = opts && opts.servicePath ? + opts.servicePath : + ((opts && opts.apiEndpoint) ? opts.apiEndpoint : + staticMembers.servicePath); const port = opts && opts.port ? opts.port : staticMembers.port; if (!opts) { @@ -92,33 +85,38 @@ export class VideoIntelligenceServiceClient { opts.port = opts.port || port; opts.clientConfig = opts.clientConfig || {}; - const isBrowser = typeof window !== 'undefined'; - if (isBrowser) { + const isBrowser = (typeof window !== 'undefined'); + if (isBrowser){ opts.fallback = true; } // If we are in browser, we are already using fallback because of the // "browser" field in package.json. // But if we were explicitly requested to use fallback, let's do it now. - const gaxModule = !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 VideoIntelligenceServiceClient).scopes; - const gaxGrpc = new gaxModule.GrpcClient(opts); + opts.scopes = (this.constructor as typeof VideoIntelligenceServiceClient).scopes; + 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}`, `gapic/${version}`]; + const clientHeader = [ + `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}`); @@ -127,74 +125,77 @@ export class VideoIntelligenceServiceClient { // For Node.js, pass the path to JSON proto file. // For browsers, pass the JSON content. - const nodejsProtoPath = path.join( - __dirname, - '..', - '..', - 'protos', - 'protos.json' - ); - const protos = gaxGrpc.loadProto( - opts.fallback ? require('../../protos/protos.json') : nodejsProtoPath + const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); + this._protos = this._gaxGrpc.loadProto( + opts.fallback ? + require("../../protos/protos.json") : + nodejsProtoPath ); // This API contains "long-running operations", which return a // an Operation object that allows for tracking of the operation, // rather than holding a request open. - const protoFilesRoot = opts.fallback - ? gaxModule.protobuf.Root.fromJSON(require('../../protos/protos.json')) - : gaxModule.protobuf.loadSync(nodejsProtoPath); - - this.operationsClient = gaxModule - .lro({ - auth: this.auth, - grpc: 'grpc' in gaxGrpc ? gaxGrpc.grpc : undefined, - }) - .operationsClient(opts); + const protoFilesRoot = opts.fallback? + this._gaxModule.protobuf.Root.fromJSON(require("../../protos/protos.json")) : + this._gaxModule.protobuf.loadSync(nodejsProtoPath); + + this.operationsClient = this._gaxModule.lro({ + auth: this.auth, + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + }).operationsClient(opts); const annotateVideoResponse = protoFilesRoot.lookup( - '.google.cloud.videointelligence.v1p2beta1.AnnotateVideoResponse' - ) as gax.protobuf.Type; + '.google.cloud.videointelligence.v1p2beta1.AnnotateVideoResponse') as gax.protobuf.Type; const annotateVideoMetadata = protoFilesRoot.lookup( - '.google.cloud.videointelligence.v1p2beta1.AnnotateVideoProgress' - ) as gax.protobuf.Type; + '.google.cloud.videointelligence.v1p2beta1.AnnotateVideoProgress') as gax.protobuf.Type; this._descriptors.longrunning = { - annotateVideo: new gaxModule.LongrunningDescriptor( + annotateVideo: new this._gaxModule.LongrunningDescriptor( this.operationsClient, annotateVideoResponse.decode.bind(annotateVideoResponse), - annotateVideoMetadata.decode.bind(annotateVideoMetadata) - ), + annotateVideoMetadata.decode.bind(annotateVideoMetadata)) }; // Put together the default options sent with requests. - const defaults = gaxGrpc.constructSettings( - 'google.cloud.videointelligence.v1p2beta1.VideoIntelligenceService', - gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, - {'x-goog-api-client': clientHeader.join(' ')} - ); + this._defaults = this._gaxGrpc.constructSettings( + 'google.cloud.videointelligence.v1p2beta1.VideoIntelligenceService', gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code // 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.videoIntelligenceServiceStub) { + return this.videoIntelligenceServiceStub; + } // Put together the "service stub" for // google.cloud.videointelligence.v1p2beta1.VideoIntelligenceService. - this.videoIntelligenceServiceStub = gaxGrpc.createStub( - opts.fallback - ? (protos as protobuf.Root).lookupService( - 'google.cloud.videointelligence.v1p2beta1.VideoIntelligenceService' - ) - : // tslint:disable-next-line no-any - (protos as any).google.cloud.videointelligence.v1p2beta1 - .VideoIntelligenceService, - opts - ) as Promise<{[method: string]: Function}>; + this.videoIntelligenceServiceStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.cloud.videointelligence.v1p2beta1.VideoIntelligenceService') : + // tslint:disable-next-line no-any + (this._protos as any).google.cloud.videointelligence.v1p2beta1.VideoIntelligenceService, + 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. - const videoIntelligenceServiceStubMethods = ['annotateVideo']; + const videoIntelligenceServiceStubMethods = + ['annotateVideo']; for (const methodName of videoIntelligenceServiceStubMethods) { const innerCallPromise = this.videoIntelligenceServiceStub.then( @@ -204,17 +205,16 @@ export class VideoIntelligenceServiceClient { } return stub[methodName].apply(stub, args); }, - (err: Error | null | undefined) => () => { + (err: Error|null|undefined) => () => { 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] + this._descriptors.stream[methodName] || + this._descriptors.longrunning[methodName] ); this._innerApiCalls[methodName] = ( @@ -225,6 +225,8 @@ export class VideoIntelligenceServiceClient { return apiCall(argument, callOptions, callback); }; } + + return this.videoIntelligenceServiceStub; } /** @@ -254,7 +256,9 @@ export class VideoIntelligenceServiceClient { * in this service. */ static get scopes() { - return ['https://www.googleapis.com/auth/cloud-platform']; + return [ + 'https://www.googleapis.com/auth/cloud-platform' + ]; } getProjectId(): Promise; @@ -264,9 +268,8 @@ export class VideoIntelligenceServiceClient { * @param {function(Error, string)} callback - the callback to * be called with the current project Id. */ - getProjectId( - callback?: Callback - ): Promise | void { + getProjectId(callback?: Callback): + Promise|void { if (callback) { this.auth.getProjectId(callback); return; @@ -279,113 +282,87 @@ export class VideoIntelligenceServiceClient { // ------------------- annotateVideo( - request: protosTypes.google.cloud.videointelligence.v1p2beta1.IAnnotateVideoRequest, - options?: gax.CallOptions - ): Promise< - [ - LROperation< - protosTypes.google.cloud.videointelligence.v1p2beta1.IAnnotateVideoResponse, - protosTypes.google.cloud.videointelligence.v1p2beta1.IAnnotateVideoProgress - >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined - ] - >; + request: protosTypes.google.cloud.videointelligence.v1p2beta1.IAnnotateVideoRequest, + options?: gax.CallOptions): + Promise<[ + LROperation, + protosTypes.google.longrunning.IOperation|undefined, {}|undefined + ]>; annotateVideo( - request: protosTypes.google.cloud.videointelligence.v1p2beta1.IAnnotateVideoRequest, - options: gax.CallOptions, - callback: Callback< - LROperation< - protosTypes.google.cloud.videointelligence.v1p2beta1.IAnnotateVideoResponse, - protosTypes.google.cloud.videointelligence.v1p2beta1.IAnnotateVideoProgress - >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined - > - ): void; - /** - * Performs asynchronous video annotation. Progress and results can be - * retrieved through the `google.longrunning.Operations` interface. - * `Operation.metadata` contains `AnnotateVideoProgress` (progress). - * `Operation.response` contains `AnnotateVideoResponse` (results). - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.inputUri - * Input video location. Currently, only - * [Google Cloud Storage](https://cloud.google.com/storage/) URIs are - * supported, which must be specified in the following format: - * `gs://bucket-id/object-id` (other URI formats return - * [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For more information, see - * [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). - * A video URI may include wildcards in `object-id`, and thus identify - * multiple videos. Supported wildcards: '*' to match 0 or more characters; - * '?' to match 1 character. If unset, the input video should be embedded - * in the request as `input_content`. If set, `input_content` should be unset. - * @param {Buffer} request.inputContent - * The video data bytes. - * If unset, the input video(s) should be specified via `input_uri`. - * If set, `input_uri` should be unset. - * @param {number[]} request.features - * Required. Requested video annotation features. - * @param {google.cloud.videointelligence.v1p2beta1.VideoContext} request.videoContext - * Additional video context and/or feature-specific parameters. - * @param {string} [request.outputUri] - * Optional. Location where the output (in JSON format) should be stored. - * Currently, only [Google Cloud Storage](https://cloud.google.com/storage/) - * URIs are supported, which must be specified in the following format: - * `gs://bucket-id/object-id` (other URI formats return - * [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For more information, see - * [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). - * @param {string} [request.locationId] - * Optional. Cloud region where annotation should take place. Supported cloud - * regions: `us-east1`, `us-west1`, `europe-west1`, `asia-east1`. If no region - * is specified, a region will be determined based on video file location. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [Operation]{@link google.longrunning.Operation}. - * The promise has a method named "cancel" which cancels the ongoing API call. - */ + request: protosTypes.google.cloud.videointelligence.v1p2beta1.IAnnotateVideoRequest, + options: gax.CallOptions, + callback: Callback< + LROperation, + protosTypes.google.longrunning.IOperation|undefined, + {}|undefined>): void; +/** + * Performs asynchronous video annotation. Progress and results can be + * retrieved through the `google.longrunning.Operations` interface. + * `Operation.metadata` contains `AnnotateVideoProgress` (progress). + * `Operation.response` contains `AnnotateVideoResponse` (results). + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.inputUri + * Input video location. Currently, only + * [Google Cloud Storage](https://cloud.google.com/storage/) URIs are + * supported, which must be specified in the following format: + * `gs://bucket-id/object-id` (other URI formats return + * {@link google.rpc.Code.INVALID_ARGUMENT|google.rpc.Code.INVALID_ARGUMENT}). For more information, see + * [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). + * A video URI may include wildcards in `object-id`, and thus identify + * multiple videos. Supported wildcards: '*' to match 0 or more characters; + * '?' to match 1 character. If unset, the input video should be embedded + * in the request as `input_content`. If set, `input_content` should be unset. + * @param {Buffer} request.inputContent + * The video data bytes. + * If unset, the input video(s) should be specified via `input_uri`. + * If set, `input_uri` should be unset. + * @param {number[]} request.features + * Required. Requested video annotation features. + * @param {google.cloud.videointelligence.v1p2beta1.VideoContext} request.videoContext + * Additional video context and/or feature-specific parameters. + * @param {string} [request.outputUri] + * Optional. Location where the output (in JSON format) should be stored. + * Currently, only [Google Cloud Storage](https://cloud.google.com/storage/) + * URIs are supported, which must be specified in the following format: + * `gs://bucket-id/object-id` (other URI formats return + * {@link google.rpc.Code.INVALID_ARGUMENT|google.rpc.Code.INVALID_ARGUMENT}). For more information, see + * [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). + * @param {string} [request.locationId] + * Optional. Cloud region where annotation should take place. Supported cloud + * regions: `us-east1`, `us-west1`, `europe-west1`, `asia-east1`. If no region + * is specified, a region will be determined based on video file location. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing [Operation]{@link google.longrunning.Operation}. + * The promise has a method named "cancel" which cancels the ongoing API call. + */ annotateVideo( - request: protosTypes.google.cloud.videointelligence.v1p2beta1.IAnnotateVideoRequest, - optionsOrCallback?: - | gax.CallOptions - | Callback< - LROperation< - protosTypes.google.cloud.videointelligence.v1p2beta1.IAnnotateVideoResponse, - protosTypes.google.cloud.videointelligence.v1p2beta1.IAnnotateVideoProgress - >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined - >, - callback?: Callback< - LROperation< - protosTypes.google.cloud.videointelligence.v1p2beta1.IAnnotateVideoResponse, - protosTypes.google.cloud.videointelligence.v1p2beta1.IAnnotateVideoProgress - >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined - > - ): Promise< - [ - LROperation< - protosTypes.google.cloud.videointelligence.v1p2beta1.IAnnotateVideoResponse, - protosTypes.google.cloud.videointelligence.v1p2beta1.IAnnotateVideoProgress - >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined - ] - > | void { + request: protosTypes.google.cloud.videointelligence.v1p2beta1.IAnnotateVideoRequest, + optionsOrCallback?: gax.CallOptions|Callback< + LROperation, + protosTypes.google.longrunning.IOperation|undefined, {}|undefined>, + callback?: Callback< + LROperation, + protosTypes.google.longrunning.IOperation|undefined, + {}|undefined>): + Promise<[ + LROperation, + protosTypes.google.longrunning.IOperation|undefined, {}|undefined + ]>|void { request = request || {}; let options: gax.CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as gax.CallOptions; } options = options || {}; + this.initialize(); return this._innerApiCalls.annotateVideo(request, options, callback); } @@ -395,8 +372,9 @@ export class VideoIntelligenceServiceClient { * The client will no longer be usable and all future behavior is undefined. */ close(): Promise { + this.initialize(); if (!this._terminated) { - return this.videoIntelligenceServiceStub.then(stub => { + return this.videoIntelligenceServiceStub!.then(stub => { this._terminated = true; stub.close(); }); diff --git a/src/v1p3beta1/index.ts b/src/v1p3beta1/index.ts index f24651ba..829cb54c 100644 --- a/src/v1p3beta1/index.ts +++ b/src/v1p3beta1/index.ts @@ -16,5 +16,4 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -export {StreamingVideoIntelligenceServiceClient} from './streaming_video_intelligence_service_client'; -export {VideoIntelligenceServiceClient} from './video_intelligence_service_client'; +export {StreamingVideoIntelligenceServiceClient} from './streaming_video_intelligence_service_client';export {VideoIntelligenceServiceClient} from './video_intelligence_service_client'; diff --git a/src/v1p3beta1/streaming_video_intelligence_service_client.ts b/src/v1p3beta1/streaming_video_intelligence_service_client.ts index 02017302..96943223 100644 --- a/src/v1p3beta1/streaming_video_intelligence_service_client.ts +++ b/src/v1p3beta1/streaming_video_intelligence_service_client.ts @@ -17,13 +17,7 @@ // ** All changes to this file may be overwritten. ** import * as gax from 'google-gax'; -import { - APICallback, - Callback, - CallOptions, - Descriptors, - ClientOptions, -} from 'google-gax'; +import {APICallback, Callback, CallOptions, Descriptors, ClientOptions} from 'google-gax'; import * as path from 'path'; import * as protosTypes from '../../protos/protos'; @@ -40,8 +34,13 @@ export class StreamingVideoIntelligenceServiceClient { 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; - streamingVideoIntelligenceServiceStub: Promise<{[name: string]: Function}>; + streamingVideoIntelligenceServiceStub?: Promise<{[name: string]: Function}>; /** * Construct an instance of StreamingVideoIntelligenceServiceClient. @@ -65,22 +64,17 @@ export class StreamingVideoIntelligenceServiceClient { * app is running in an environment which supports * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, * your project ID will be detected automatically. - * @param {function} [options.promise] - Custom promise module to use instead - * of native Promises. * @param {string} [options.apiEndpoint] - The domain name of the * API remote host. */ constructor(opts?: ClientOptions) { // Ensure that options include the service address and port. - const staticMembers = this - .constructor as typeof StreamingVideoIntelligenceServiceClient; - const servicePath = - opts && opts.servicePath - ? opts.servicePath - : opts && opts.apiEndpoint - ? opts.apiEndpoint - : staticMembers.servicePath; + const staticMembers = this.constructor as typeof StreamingVideoIntelligenceServiceClient; + const servicePath = opts && opts.servicePath ? + opts.servicePath : + ((opts && opts.apiEndpoint) ? opts.apiEndpoint : + staticMembers.servicePath); const port = opts && opts.port ? opts.port : staticMembers.port; if (!opts) { @@ -90,33 +84,38 @@ export class StreamingVideoIntelligenceServiceClient { opts.port = opts.port || port; opts.clientConfig = opts.clientConfig || {}; - const isBrowser = typeof window !== 'undefined'; - if (isBrowser) { + const isBrowser = (typeof window !== 'undefined'); + if (isBrowser){ opts.fallback = true; } // If we are in browser, we are already using fallback because of the // "browser" field in package.json. // But if we were explicitly requested to use fallback, let's do it now. - const gaxModule = !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 StreamingVideoIntelligenceServiceClient).scopes; - const gaxGrpc = new gaxModule.GrpcClient(opts); + opts.scopes = (this.constructor as typeof StreamingVideoIntelligenceServiceClient).scopes; + 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}`, `gapic/${version}`]; + const clientHeader = [ + `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,56 +124,60 @@ export class StreamingVideoIntelligenceServiceClient { // For Node.js, pass the path to JSON proto file. // For browsers, pass the JSON content. - const nodejsProtoPath = path.join( - __dirname, - '..', - '..', - 'protos', - 'protos.json' - ); - const protos = gaxGrpc.loadProto( - opts.fallback ? require('../../protos/protos.json') : nodejsProtoPath + const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); + this._protos = this._gaxGrpc.loadProto( + opts.fallback ? + require("../../protos/protos.json") : + nodejsProtoPath ); // Some of the methods on this service provide streaming responses. // Provide descriptors for these. this._descriptors.stream = { - streamingAnnotateVideo: new gaxModule.StreamDescriptor( - gax.StreamType.BIDI_STREAMING - ), + streamingAnnotateVideo: new this._gaxModule.StreamDescriptor(gax.StreamType.BIDI_STREAMING) }; // Put together the default options sent with requests. - const defaults = gaxGrpc.constructSettings( - 'google.cloud.videointelligence.v1p3beta1.StreamingVideoIntelligenceService', - gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, - {'x-goog-api-client': clientHeader.join(' ')} - ); + this._defaults = this._gaxGrpc.constructSettings( + 'google.cloud.videointelligence.v1p3beta1.StreamingVideoIntelligenceService', gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code // 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.streamingVideoIntelligenceServiceStub) { + return this.streamingVideoIntelligenceServiceStub; + } // Put together the "service stub" for // google.cloud.videointelligence.v1p3beta1.StreamingVideoIntelligenceService. - this.streamingVideoIntelligenceServiceStub = gaxGrpc.createStub( - opts.fallback - ? (protos as protobuf.Root).lookupService( - 'google.cloud.videointelligence.v1p3beta1.StreamingVideoIntelligenceService' - ) - : // tslint:disable-next-line no-any - (protos as any).google.cloud.videointelligence.v1p3beta1 - .StreamingVideoIntelligenceService, - opts - ) as Promise<{[method: string]: Function}>; + this.streamingVideoIntelligenceServiceStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.cloud.videointelligence.v1p3beta1.StreamingVideoIntelligenceService') : + // tslint:disable-next-line no-any + (this._protos as any).google.cloud.videointelligence.v1p3beta1.StreamingVideoIntelligenceService, + 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. - const streamingVideoIntelligenceServiceStubMethods = [ - 'streamingAnnotateVideo', - ]; + const streamingVideoIntelligenceServiceStubMethods = + ['streamingAnnotateVideo']; for (const methodName of streamingVideoIntelligenceServiceStubMethods) { const innerCallPromise = this.streamingVideoIntelligenceServiceStub.then( @@ -184,17 +187,16 @@ export class StreamingVideoIntelligenceServiceClient { } return stub[methodName].apply(stub, args); }, - (err: Error | null | undefined) => () => { + (err: Error|null|undefined) => () => { 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] + this._descriptors.stream[methodName] || + this._descriptors.longrunning[methodName] ); this._innerApiCalls[methodName] = ( @@ -205,6 +207,8 @@ export class StreamingVideoIntelligenceServiceClient { return apiCall(argument, callOptions, callback); }; } + + return this.streamingVideoIntelligenceServiceStub; } /** @@ -234,7 +238,9 @@ export class StreamingVideoIntelligenceServiceClient { * in this service. */ static get scopes() { - return ['https://www.googleapis.com/auth/cloud-platform']; + return [ + 'https://www.googleapis.com/auth/cloud-platform' + ]; } getProjectId(): Promise; @@ -244,9 +250,8 @@ export class StreamingVideoIntelligenceServiceClient { * @param {function(Error, string)} callback - the callback to * be called with the current project Id. */ - getProjectId( - callback?: Callback - ): Promise | void { + getProjectId(callback?: Callback): + Promise|void { if (callback) { this.auth.getProjectId(callback); return; @@ -258,30 +263,35 @@ export class StreamingVideoIntelligenceServiceClient { // -- Service calls -- // ------------------- - /** - * Performs video annotation with bidirectional streaming: emitting results - * while sending video/audio bytes. - * This method is only available via the gRPC API (not REST). - * - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Stream} - * An object stream which is both readable and writable. It accepts objects - * representing [StreamingAnnotateVideoRequest]{@link google.cloud.videointelligence.v1p3beta1.StreamingAnnotateVideoRequest} for write() method, and - * will emit objects representing [StreamingAnnotateVideoResponse]{@link google.cloud.videointelligence.v1p3beta1.StreamingAnnotateVideoResponse} on 'data' event asynchronously. - */ - streamingAnnotateVideo(options?: gax.CallOptions): gax.CancellableStream { +/** + * Performs video annotation with bidirectional streaming: emitting results + * while sending video/audio bytes. + * This method is only available via the gRPC API (not REST). + * + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Stream} + * An object stream which is both readable and writable. It accepts objects + * representing [StreamingAnnotateVideoRequest]{@link google.cloud.videointelligence.v1p3beta1.StreamingAnnotateVideoRequest} for write() method, and + * will emit objects representing [StreamingAnnotateVideoResponse]{@link google.cloud.videointelligence.v1p3beta1.StreamingAnnotateVideoResponse} on 'data' event asynchronously. + */ + streamingAnnotateVideo( + options?: gax.CallOptions): + gax.CancellableStream { + this.initialize(); return this._innerApiCalls.streamingAnnotateVideo(options); } + /** * Terminate the GRPC channel and close the client. * * The client will no longer be usable and all future behavior is undefined. */ close(): Promise { + this.initialize(); if (!this._terminated) { - return this.streamingVideoIntelligenceServiceStub.then(stub => { + return this.streamingVideoIntelligenceServiceStub!.then(stub => { this._terminated = true; stub.close(); }); diff --git a/src/v1p3beta1/video_intelligence_service_client.ts b/src/v1p3beta1/video_intelligence_service_client.ts index afeef905..279d9fa8 100644 --- a/src/v1p3beta1/video_intelligence_service_client.ts +++ b/src/v1p3beta1/video_intelligence_service_client.ts @@ -17,14 +17,7 @@ // ** All changes to this file may be overwritten. ** import * as gax from 'google-gax'; -import { - APICallback, - Callback, - CallOptions, - Descriptors, - ClientOptions, - LROperation, -} from 'google-gax'; +import {APICallback, Callback, CallOptions, Descriptors, ClientOptions, LROperation} from 'google-gax'; import * as path from 'path'; import * as protosTypes from '../../protos/protos'; @@ -41,9 +34,14 @@ export class VideoIntelligenceServiceClient { 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; operationsClient: gax.OperationsClient; - videoIntelligenceServiceStub: Promise<{[name: string]: Function}>; + videoIntelligenceServiceStub?: Promise<{[name: string]: Function}>; /** * Construct an instance of VideoIntelligenceServiceClient. @@ -67,22 +65,17 @@ export class VideoIntelligenceServiceClient { * app is running in an environment which supports * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, * your project ID will be detected automatically. - * @param {function} [options.promise] - Custom promise module to use instead - * of native Promises. * @param {string} [options.apiEndpoint] - The domain name of the * API remote host. */ constructor(opts?: ClientOptions) { // Ensure that options include the service address and port. - const staticMembers = this - .constructor as typeof VideoIntelligenceServiceClient; - const servicePath = - opts && opts.servicePath - ? opts.servicePath - : opts && opts.apiEndpoint - ? opts.apiEndpoint - : staticMembers.servicePath; + const staticMembers = this.constructor as typeof VideoIntelligenceServiceClient; + const servicePath = opts && opts.servicePath ? + opts.servicePath : + ((opts && opts.apiEndpoint) ? opts.apiEndpoint : + staticMembers.servicePath); const port = opts && opts.port ? opts.port : staticMembers.port; if (!opts) { @@ -92,33 +85,38 @@ export class VideoIntelligenceServiceClient { opts.port = opts.port || port; opts.clientConfig = opts.clientConfig || {}; - const isBrowser = typeof window !== 'undefined'; - if (isBrowser) { + const isBrowser = (typeof window !== 'undefined'); + if (isBrowser){ opts.fallback = true; } // If we are in browser, we are already using fallback because of the // "browser" field in package.json. // But if we were explicitly requested to use fallback, let's do it now. - const gaxModule = !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 VideoIntelligenceServiceClient).scopes; - const gaxGrpc = new gaxModule.GrpcClient(opts); + opts.scopes = (this.constructor as typeof VideoIntelligenceServiceClient).scopes; + 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}`, `gapic/${version}`]; + const clientHeader = [ + `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}`); @@ -127,74 +125,77 @@ export class VideoIntelligenceServiceClient { // For Node.js, pass the path to JSON proto file. // For browsers, pass the JSON content. - const nodejsProtoPath = path.join( - __dirname, - '..', - '..', - 'protos', - 'protos.json' - ); - const protos = gaxGrpc.loadProto( - opts.fallback ? require('../../protos/protos.json') : nodejsProtoPath + const nodejsProtoPath = path.join(__dirname, '..', '..', 'protos', 'protos.json'); + this._protos = this._gaxGrpc.loadProto( + opts.fallback ? + require("../../protos/protos.json") : + nodejsProtoPath ); // This API contains "long-running operations", which return a // an Operation object that allows for tracking of the operation, // rather than holding a request open. - const protoFilesRoot = opts.fallback - ? gaxModule.protobuf.Root.fromJSON(require('../../protos/protos.json')) - : gaxModule.protobuf.loadSync(nodejsProtoPath); - - this.operationsClient = gaxModule - .lro({ - auth: this.auth, - grpc: 'grpc' in gaxGrpc ? gaxGrpc.grpc : undefined, - }) - .operationsClient(opts); + const protoFilesRoot = opts.fallback? + this._gaxModule.protobuf.Root.fromJSON(require("../../protos/protos.json")) : + this._gaxModule.protobuf.loadSync(nodejsProtoPath); + + this.operationsClient = this._gaxModule.lro({ + auth: this.auth, + grpc: 'grpc' in this._gaxGrpc ? this._gaxGrpc.grpc : undefined + }).operationsClient(opts); const annotateVideoResponse = protoFilesRoot.lookup( - '.google.cloud.videointelligence.v1p3beta1.AnnotateVideoResponse' - ) as gax.protobuf.Type; + '.google.cloud.videointelligence.v1p3beta1.AnnotateVideoResponse') as gax.protobuf.Type; const annotateVideoMetadata = protoFilesRoot.lookup( - '.google.cloud.videointelligence.v1p3beta1.AnnotateVideoProgress' - ) as gax.protobuf.Type; + '.google.cloud.videointelligence.v1p3beta1.AnnotateVideoProgress') as gax.protobuf.Type; this._descriptors.longrunning = { - annotateVideo: new gaxModule.LongrunningDescriptor( + annotateVideo: new this._gaxModule.LongrunningDescriptor( this.operationsClient, annotateVideoResponse.decode.bind(annotateVideoResponse), - annotateVideoMetadata.decode.bind(annotateVideoMetadata) - ), + annotateVideoMetadata.decode.bind(annotateVideoMetadata)) }; // Put together the default options sent with requests. - const defaults = gaxGrpc.constructSettings( - 'google.cloud.videointelligence.v1p3beta1.VideoIntelligenceService', - gapicConfig as gax.ClientConfig, - opts.clientConfig || {}, - {'x-goog-api-client': clientHeader.join(' ')} - ); + this._defaults = this._gaxGrpc.constructSettings( + 'google.cloud.videointelligence.v1p3beta1.VideoIntelligenceService', gapicConfig as gax.ClientConfig, + opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')}); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code // 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.videoIntelligenceServiceStub) { + return this.videoIntelligenceServiceStub; + } // Put together the "service stub" for // google.cloud.videointelligence.v1p3beta1.VideoIntelligenceService. - this.videoIntelligenceServiceStub = gaxGrpc.createStub( - opts.fallback - ? (protos as protobuf.Root).lookupService( - 'google.cloud.videointelligence.v1p3beta1.VideoIntelligenceService' - ) - : // tslint:disable-next-line no-any - (protos as any).google.cloud.videointelligence.v1p3beta1 - .VideoIntelligenceService, - opts - ) as Promise<{[method: string]: Function}>; + this.videoIntelligenceServiceStub = this._gaxGrpc.createStub( + this._opts.fallback ? + (this._protos as protobuf.Root).lookupService('google.cloud.videointelligence.v1p3beta1.VideoIntelligenceService') : + // tslint:disable-next-line no-any + (this._protos as any).google.cloud.videointelligence.v1p3beta1.VideoIntelligenceService, + 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. - const videoIntelligenceServiceStubMethods = ['annotateVideo']; + const videoIntelligenceServiceStubMethods = + ['annotateVideo']; for (const methodName of videoIntelligenceServiceStubMethods) { const innerCallPromise = this.videoIntelligenceServiceStub.then( @@ -204,17 +205,16 @@ export class VideoIntelligenceServiceClient { } return stub[methodName].apply(stub, args); }, - (err: Error | null | undefined) => () => { + (err: Error|null|undefined) => () => { 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] + this._descriptors.stream[methodName] || + this._descriptors.longrunning[methodName] ); this._innerApiCalls[methodName] = ( @@ -225,6 +225,8 @@ export class VideoIntelligenceServiceClient { return apiCall(argument, callOptions, callback); }; } + + return this.videoIntelligenceServiceStub; } /** @@ -254,7 +256,9 @@ export class VideoIntelligenceServiceClient { * in this service. */ static get scopes() { - return ['https://www.googleapis.com/auth/cloud-platform']; + return [ + 'https://www.googleapis.com/auth/cloud-platform' + ]; } getProjectId(): Promise; @@ -264,9 +268,8 @@ export class VideoIntelligenceServiceClient { * @param {function(Error, string)} callback - the callback to * be called with the current project Id. */ - getProjectId( - callback?: Callback - ): Promise | void { + getProjectId(callback?: Callback): + Promise|void { if (callback) { this.auth.getProjectId(callback); return; @@ -279,113 +282,87 @@ export class VideoIntelligenceServiceClient { // ------------------- annotateVideo( - request: protosTypes.google.cloud.videointelligence.v1p3beta1.IAnnotateVideoRequest, - options?: gax.CallOptions - ): Promise< - [ - LROperation< - protosTypes.google.cloud.videointelligence.v1p3beta1.IAnnotateVideoResponse, - protosTypes.google.cloud.videointelligence.v1p3beta1.IAnnotateVideoProgress - >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined - ] - >; + request: protosTypes.google.cloud.videointelligence.v1p3beta1.IAnnotateVideoRequest, + options?: gax.CallOptions): + Promise<[ + LROperation, + protosTypes.google.longrunning.IOperation|undefined, {}|undefined + ]>; annotateVideo( - request: protosTypes.google.cloud.videointelligence.v1p3beta1.IAnnotateVideoRequest, - options: gax.CallOptions, - callback: Callback< - LROperation< - protosTypes.google.cloud.videointelligence.v1p3beta1.IAnnotateVideoResponse, - protosTypes.google.cloud.videointelligence.v1p3beta1.IAnnotateVideoProgress - >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined - > - ): void; - /** - * Performs asynchronous video annotation. Progress and results can be - * retrieved through the `google.longrunning.Operations` interface. - * `Operation.metadata` contains `AnnotateVideoProgress` (progress). - * `Operation.response` contains `AnnotateVideoResponse` (results). - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.inputUri - * Input video location. Currently, only - * [Google Cloud Storage](https://cloud.google.com/storage/) URIs are - * supported, which must be specified in the following format: - * `gs://bucket-id/object-id` (other URI formats return - * [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For - * more information, see [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). A video - * URI may include wildcards in `object-id`, and thus identify multiple - * videos. Supported wildcards: '*' to match 0 or more characters; - * '?' to match 1 character. If unset, the input video should be embedded - * in the request as `input_content`. If set, `input_content` should be unset. - * @param {Buffer} request.inputContent - * The video data bytes. - * If unset, the input video(s) should be specified via `input_uri`. - * If set, `input_uri` should be unset. - * @param {number[]} request.features - * Required. Requested video annotation features. - * @param {google.cloud.videointelligence.v1p3beta1.VideoContext} request.videoContext - * Additional video context and/or feature-specific parameters. - * @param {string} [request.outputUri] - * Optional. Location where the output (in JSON format) should be stored. - * Currently, only [Google Cloud Storage](https://cloud.google.com/storage/) - * URIs are supported, which must be specified in the following format: - * `gs://bucket-id/object-id` (other URI formats return - * [google.rpc.Code.INVALID_ARGUMENT][google.rpc.Code.INVALID_ARGUMENT]). For - * more information, see [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). - * @param {string} [request.locationId] - * Optional. Cloud region where annotation should take place. Supported cloud - * regions: `us-east1`, `us-west1`, `europe-west1`, `asia-east1`. If no region - * is specified, a region will be determined based on video file location. - * @param {object} [options] - * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. - * @returns {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [Operation]{@link google.longrunning.Operation}. - * The promise has a method named "cancel" which cancels the ongoing API call. - */ + request: protosTypes.google.cloud.videointelligence.v1p3beta1.IAnnotateVideoRequest, + options: gax.CallOptions, + callback: Callback< + LROperation, + protosTypes.google.longrunning.IOperation|undefined, + {}|undefined>): void; +/** + * Performs asynchronous video annotation. Progress and results can be + * retrieved through the `google.longrunning.Operations` interface. + * `Operation.metadata` contains `AnnotateVideoProgress` (progress). + * `Operation.response` contains `AnnotateVideoResponse` (results). + * + * @param {Object} request + * The request object that will be sent. + * @param {string} request.inputUri + * Input video location. Currently, only + * [Google Cloud Storage](https://cloud.google.com/storage/) URIs are + * supported, which must be specified in the following format: + * `gs://bucket-id/object-id` (other URI formats return + * {@link google.rpc.Code.INVALID_ARGUMENT|google.rpc.Code.INVALID_ARGUMENT}). For + * more information, see [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). A video + * URI may include wildcards in `object-id`, and thus identify multiple + * videos. Supported wildcards: '*' to match 0 or more characters; + * '?' to match 1 character. If unset, the input video should be embedded + * in the request as `input_content`. If set, `input_content` should be unset. + * @param {Buffer} request.inputContent + * The video data bytes. + * If unset, the input video(s) should be specified via `input_uri`. + * If set, `input_uri` should be unset. + * @param {number[]} request.features + * Required. Requested video annotation features. + * @param {google.cloud.videointelligence.v1p3beta1.VideoContext} request.videoContext + * Additional video context and/or feature-specific parameters. + * @param {string} [request.outputUri] + * Optional. Location where the output (in JSON format) should be stored. + * Currently, only [Google Cloud Storage](https://cloud.google.com/storage/) + * URIs are supported, which must be specified in the following format: + * `gs://bucket-id/object-id` (other URI formats return + * {@link google.rpc.Code.INVALID_ARGUMENT|google.rpc.Code.INVALID_ARGUMENT}). For + * more information, see [Request URIs](https://cloud.google.com/storage/docs/request-endpoints). + * @param {string} [request.locationId] + * Optional. Cloud region where annotation should take place. Supported cloud + * regions: `us-east1`, `us-west1`, `europe-west1`, `asia-east1`. If no region + * is specified, a region will be determined based on video file location. + * @param {object} [options] + * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. + * @returns {Promise} - The promise which resolves to an array. + * The first element of the array is an object representing [Operation]{@link google.longrunning.Operation}. + * The promise has a method named "cancel" which cancels the ongoing API call. + */ annotateVideo( - request: protosTypes.google.cloud.videointelligence.v1p3beta1.IAnnotateVideoRequest, - optionsOrCallback?: - | gax.CallOptions - | Callback< - LROperation< - protosTypes.google.cloud.videointelligence.v1p3beta1.IAnnotateVideoResponse, - protosTypes.google.cloud.videointelligence.v1p3beta1.IAnnotateVideoProgress - >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined - >, - callback?: Callback< - LROperation< - protosTypes.google.cloud.videointelligence.v1p3beta1.IAnnotateVideoResponse, - protosTypes.google.cloud.videointelligence.v1p3beta1.IAnnotateVideoProgress - >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined - > - ): Promise< - [ - LROperation< - protosTypes.google.cloud.videointelligence.v1p3beta1.IAnnotateVideoResponse, - protosTypes.google.cloud.videointelligence.v1p3beta1.IAnnotateVideoProgress - >, - protosTypes.google.longrunning.IOperation | undefined, - {} | undefined - ] - > | void { + request: protosTypes.google.cloud.videointelligence.v1p3beta1.IAnnotateVideoRequest, + optionsOrCallback?: gax.CallOptions|Callback< + LROperation, + protosTypes.google.longrunning.IOperation|undefined, {}|undefined>, + callback?: Callback< + LROperation, + protosTypes.google.longrunning.IOperation|undefined, + {}|undefined>): + Promise<[ + LROperation, + protosTypes.google.longrunning.IOperation|undefined, {}|undefined + ]>|void { request = request || {}; let options: gax.CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; - } else { + } + else { options = optionsOrCallback as gax.CallOptions; } options = options || {}; + this.initialize(); return this._innerApiCalls.annotateVideo(request, options, callback); } @@ -395,8 +372,9 @@ export class VideoIntelligenceServiceClient { * The client will no longer be usable and all future behavior is undefined. */ close(): Promise { + this.initialize(); if (!this._terminated) { - return this.videoIntelligenceServiceStub.then(stub => { + return this.videoIntelligenceServiceStub!.then(stub => { this._terminated = true; stub.close(); }); diff --git a/synth.metadata b/synth.metadata index b8c94543..4adf647d 100644 --- a/synth.metadata +++ b/synth.metadata @@ -1,13 +1,13 @@ { - "updateTime": "2020-03-05T22:26:31.988229Z", + "updateTime": "2020-03-09T11:45:53.267362Z", "sources": [ { "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "f0b581b5bdf803e45201ecdb3688b60e381628a8", - "internalRef": "299181282", - "log": "f0b581b5bdf803e45201ecdb3688b60e381628a8\nfix: recommendationengine/v1beta1 update some comments\n\nPiperOrigin-RevId: 299181282\n\n10e9a0a833dc85ff8f05b2c67ebe5ac785fe04ff\nbuild: add generated BUILD file for Routes Preferred API\n\nPiperOrigin-RevId: 299164808\n\n86738c956a8238d7c77f729be78b0ed887a6c913\npublish v1p1beta1: update with absolute address in comments\n\nPiperOrigin-RevId: 299152383\n\n73d9f2ad4591de45c2e1f352bc99d70cbd2a6d95\npublish v1: update with absolute address in comments\n\nPiperOrigin-RevId: 299147194\n\nd2158f24cb77b0b0ccfe68af784c6a628705e3c6\npublish v1beta2: update with absolute address in comments\n\nPiperOrigin-RevId: 299147086\n\n7fca61292c11b4cd5b352cee1a50bf88819dd63b\npublish v1p2beta1: update with absolute address in comments\n\nPiperOrigin-RevId: 299146903\n\n583b7321624736e2c490e328f4b1957335779295\npublish v1p3beta1: update with absolute address in comments\n\nPiperOrigin-RevId: 299146674\n\n638253bf86d1ce1c314108a089b7351440c2f0bf\nfix: add java_multiple_files option for automl text_sentiment.proto\n\nPiperOrigin-RevId: 298971070\n\n373d655703bf914fb8b0b1cc4071d772bac0e0d1\nUpdate Recs AI Beta public bazel file\n\nPiperOrigin-RevId: 298961623\n\ndcc5d00fc8a8d8b56f16194d7c682027b2c66a3b\nfix: add java_multiple_files option for automl classification.proto\n\nPiperOrigin-RevId: 298953301\n\na3f791827266f3496a6a5201d58adc4bb265c2a3\nchore: automl/v1 publish annotations and retry config\n\nPiperOrigin-RevId: 298942178\n\n01c681586d8d6dbd60155289b587aee678530bd9\nMark return_immediately in PullRequest deprecated.\n\nPiperOrigin-RevId: 298893281\n\nc9f5e9c4bfed54bbd09227e990e7bded5f90f31c\nRemove out of date documentation for predicate support on the Storage API\n\nPiperOrigin-RevId: 298883309\n\nfd5b3b8238d783b04692a113ffe07c0363f5de0f\ngenerate webrisk v1 proto\n\nPiperOrigin-RevId: 298847934\n\n" + "sha": "af7dff701fabe029672168649c62356cf1bb43d0", + "internalRef": "299724050", + "log": "af7dff701fabe029672168649c62356cf1bb43d0\nAdd LogPlayerReports and LogImpressions to Playable Locations service\n\nPiperOrigin-RevId: 299724050\n\nb6927fca808f38df32a642c560082f5bf6538ced\nUpdate BigQuery Connection API v1beta1 proto: added credential to CloudSqlProperties.\n\nPiperOrigin-RevId: 299503150\n\n91e1fb5ef9829c0c7a64bfa5bde330e6ed594378\nchore: update protobuf (protoc) version to 3.11.2\n\nPiperOrigin-RevId: 299404145\n\n30e36b4bee6749c4799f4fc1a51cc8f058ba167d\nUpdate cloud asset api v1p4beta1.\n\nPiperOrigin-RevId: 299399890\n\nffbb493674099f265693872ae250711b2238090c\nfeat: cloudbuild/v1 add new fields and annotate OUTPUT_OUT fields.\n\nPiperOrigin-RevId: 299397780\n\nbc973a15818e00c19e121959832676e9b7607456\nbazel: Fix broken common dependency\n\nPiperOrigin-RevId: 299397431\n\n71094a343e3b962e744aa49eb9338219537474e4\nchore: bigtable/admin/v2 publish retry config\n\nPiperOrigin-RevId: 299391875\n\n8f488efd7bda33885cb674ddd023b3678c40bd82\nfeat: Migrate logging to GAPIC v2; release new features.\n\nIMPORTANT: This is a breaking change for client libraries\nin all languages.\n\nCommitter: @lukesneeringer, @jskeet\nPiperOrigin-RevId: 299370279\n\n007605bf9ad3a1fd775014ebefbf7f1e6b31ee71\nUpdate API for bigqueryreservation v1beta1.\n- Adds flex capacity commitment plan to CapacityCommitment.\n- Adds methods for getting and updating BiReservations.\n- Adds methods for updating/splitting/merging CapacityCommitments.\n\nPiperOrigin-RevId: 299368059\n\n" } }, { diff --git a/system-test/install.ts b/system-test/install.ts index c9aa74ec..140852a8 100644 --- a/system-test/install.ts +++ b/system-test/install.ts @@ -16,36 +16,34 @@ // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** -import {packNTest} from 'pack-n-play'; -import {readFileSync} from 'fs'; -import {describe, it} from 'mocha'; +import { packNTest } from 'pack-n-play'; +import { readFileSync } from 'fs'; +import { describe, it } from 'mocha'; describe('typescript consumer tests', () => { + it('should have correct type signature for typescript users', async function() { this.timeout(300000); const options = { - packageDir: process.cwd(), // path to your module. + packageDir: process.cwd(), // path to your module. sample: { description: 'typescript based user can use the type definitions', - ts: readFileSync( - './system-test/fixtures/sample/src/index.ts' - ).toString(), - }, + ts: readFileSync('./system-test/fixtures/sample/src/index.ts').toString() + } }; - await packNTest(options); // will throw upon error. + await packNTest(options); // will throw upon error. }); it('should have correct type signature for javascript users', async function() { this.timeout(300000); const options = { - packageDir: process.cwd(), // path to your module. + packageDir: process.cwd(), // path to your module. sample: { description: 'typescript based user can use the type definitions', - ts: readFileSync( - './system-test/fixtures/sample/src/index.js' - ).toString(), - }, + ts: readFileSync('./system-test/fixtures/sample/src/index.js').toString() + } }; - await packNTest(options); // will throw upon error. + await packNTest(options); // will throw upon error. }); + }); diff --git a/test/gapic-streaming_video_intelligence_service-v1p3beta1.ts b/test/gapic-streaming_video_intelligence_service-v1p3beta1.ts index c04259d5..1d601228 100644 --- a/test/gapic-streaming_video_intelligence_service-v1p3beta1.ts +++ b/test/gapic-streaming_video_intelligence_service-v1p3beta1.ts @@ -18,140 +18,132 @@ import * as protosTypes from '../protos/protos'; import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import { describe, it } from 'mocha'; const streamingvideointelligenceserviceModule = require('../src'); import {PassThrough} from 'stream'; + const FAKE_STATUS_CODE = 1; -class FakeError { - name: string; - message: string; - code: number; - constructor(n: number) { - this.name = 'fakeName'; - this.message = 'fake message'; - this.code = n; - } +class FakeError{ + name: string; + message: string; + code: number; + constructor(n: number){ + this.name = 'fakeName'; + this.message = 'fake message'; + this.code = n; + } } const error = new FakeError(FAKE_STATUS_CODE); export interface Callback { - (err: FakeError | null, response?: {} | null): void; + (err: FakeError|null, response?: {} | null): void; } -export class Operation { - constructor() {} - promise() {} +export class Operation{ + constructor(){}; + promise() {}; } -function mockBidiStreamingGrpcMethod( - expectedRequest: {}, - response: {} | null, - error: FakeError | null -) { - return () => { - const mockStream = new PassThrough({ - objectMode: true, - transform: (chunk: {}, enc: {}, callback: Callback) => { - assert.deepStrictEqual(chunk, expectedRequest); - if (error) { - callback(error); - } else { - callback(null, response); - } - }, - }); - return mockStream; - }; +function mockBidiStreamingGrpcMethod(expectedRequest: {}, response: {} | null, error: FakeError | null) { + return () => { + const mockStream = new PassThrough({ + objectMode: true, + transform: (chunk: {}, enc: {}, callback: Callback) => { + assert.deepStrictEqual(chunk, expectedRequest); + if (error) { + callback(error); + } + else { + callback(null, response); + } + } + }); + return mockStream; + } } describe('v1p3beta1.StreamingVideoIntelligenceServiceClient', () => { - it('has servicePath', () => { - const servicePath = - streamingvideointelligenceserviceModule.v1p3beta1 - .StreamingVideoIntelligenceServiceClient.servicePath; - assert(servicePath); - }); - it('has apiEndpoint', () => { - const apiEndpoint = - streamingvideointelligenceserviceModule.v1p3beta1 - .StreamingVideoIntelligenceServiceClient.apiEndpoint; - assert(apiEndpoint); - }); - it('has port', () => { - const port = - streamingvideointelligenceserviceModule.v1p3beta1 - .StreamingVideoIntelligenceServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - it('should create a client with no option', () => { - const client = new streamingvideointelligenceserviceModule.v1p3beta1.StreamingVideoIntelligenceServiceClient(); - assert(client); - }); - it('should create a client with gRPC fallback', () => { - const client = new streamingvideointelligenceserviceModule.v1p3beta1.StreamingVideoIntelligenceServiceClient( - { - fallback: true, - } - ); - assert(client); - }); - describe('streamingAnnotateVideo', () => { - it('invokes streamingAnnotateVideo without error', done => { - const client = new streamingvideointelligenceserviceModule.v1p3beta1.StreamingVideoIntelligenceServiceClient( - { - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - } - ); - // Mock request - const request: protosTypes.google.cloud.videointelligence.v1p3beta1.IStreamingAnnotateVideoRequest = {}; - // Mock response - const expectedResponse = {}; - // Mock gRPC layer - client._innerApiCalls.streamingAnnotateVideo = mockBidiStreamingGrpcMethod( - request, - expectedResponse, - null - ); - const stream = client - .streamingAnnotateVideo() - .on('data', (response: {}) => { - assert.deepStrictEqual(response, expectedResponse); - done(); - }) - .on('error', (err: FakeError) => { - done(err); + it('has servicePath', () => { + const servicePath = streamingvideointelligenceserviceModule.v1p3beta1.StreamingVideoIntelligenceServiceClient.servicePath; + assert(servicePath); + }); + it('has apiEndpoint', () => { + const apiEndpoint = streamingvideointelligenceserviceModule.v1p3beta1.StreamingVideoIntelligenceServiceClient.apiEndpoint; + assert(apiEndpoint); + }); + it('has port', () => { + const port = streamingvideointelligenceserviceModule.v1p3beta1.StreamingVideoIntelligenceServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); + it('should create a client with no option', () => { + const client = new streamingvideointelligenceserviceModule.v1p3beta1.StreamingVideoIntelligenceServiceClient(); + assert(client); + }); + it('should create a client with gRPC fallback', () => { + const client = new streamingvideointelligenceserviceModule.v1p3beta1.StreamingVideoIntelligenceServiceClient({ + fallback: true, + }); + assert(client); + }); + it('has initialize method and supports deferred initialization', async () => { + const client = new streamingvideointelligenceserviceModule.v1p3beta1.StreamingVideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', }); - stream.write(request); + assert.strictEqual(client.streamingVideoIntelligenceServiceStub, undefined); + await client.initialize(); + assert(client.streamingVideoIntelligenceServiceStub); }); - it('invokes streamingAnnotateVideo with error', done => { - const client = new streamingvideointelligenceserviceModule.v1p3beta1.StreamingVideoIntelligenceServiceClient( - { - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - } - ); - // Mock request - const request: protosTypes.google.cloud.videointelligence.v1p3beta1.IStreamingAnnotateVideoRequest = {}; - // Mock response - const expectedResponse = {}; - // Mock gRPC layer - client._innerApiCalls.streamingAnnotateVideo = mockBidiStreamingGrpcMethod( - request, - null, - error - ); - const stream = client - .streamingAnnotateVideo() - .on('data', () => { - assert.fail(); - }) - .on('error', (err: FakeError) => { - assert(err instanceof FakeError); - assert.strictEqual(err.code, FAKE_STATUS_CODE); - done(); + it('has close method', () => { + const client = new streamingvideointelligenceserviceModule.v1p3beta1.StreamingVideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.close(); + }); + describe('streamingAnnotateVideo', () => { + it('invokes streamingAnnotateVideo without error', done => { + const client = new streamingvideointelligenceserviceModule.v1p3beta1.StreamingVideoIntelligenceServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + // Initialize client before mocking + client.initialize(); + // Mock request + const request: protosTypes.google.cloud.videointelligence.v1p3beta1.IStreamingAnnotateVideoRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock gRPC layer + client._innerApiCalls.streamingAnnotateVideo = mockBidiStreamingGrpcMethod(request, expectedResponse, null); + const stream = client.streamingAnnotateVideo().on('data', (response: {}) =>{ + assert.deepStrictEqual(response, expectedResponse); + done(); + }).on('error', (err: FakeError) => { + done(err); + }); + stream.write(request); + }); + it('invokes streamingAnnotateVideo with error', done => { + const client = new streamingvideointelligenceserviceModule.v1p3beta1.StreamingVideoIntelligenceServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + // Initialize client before mocking + client.initialize(); + // Mock request + const request: protosTypes.google.cloud.videointelligence.v1p3beta1.IStreamingAnnotateVideoRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock gRPC layer + client._innerApiCalls.streamingAnnotateVideo = mockBidiStreamingGrpcMethod(request, null, error); + const stream = client.streamingAnnotateVideo().on('data', () =>{ + assert.fail(); + }).on('error', (err: FakeError) => { + assert(err instanceof FakeError); + assert.strictEqual(err.code, FAKE_STATUS_CODE); + done(); + }); + stream.write(request); }); - stream.write(request); }); - }); }); diff --git a/test/gapic-video_intelligence_service-v1.ts b/test/gapic-video_intelligence_service-v1.ts index f970f74f..a99b1701 100644 --- a/test/gapic-video_intelligence_service-v1.ts +++ b/test/gapic-video_intelligence_service-v1.ts @@ -18,144 +18,143 @@ import * as protosTypes from '../protos/protos'; import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import { describe, it } from 'mocha'; const videointelligenceserviceModule = require('../src'); + const FAKE_STATUS_CODE = 1; -class FakeError { - name: string; - message: string; - code: number; - constructor(n: number) { - this.name = 'fakeName'; - this.message = 'fake message'; - this.code = n; - } +class FakeError{ + name: string; + message: string; + code: number; + constructor(n: number){ + this.name = 'fakeName'; + this.message = 'fake message'; + this.code = n; + } } const error = new FakeError(FAKE_STATUS_CODE); export interface Callback { - (err: FakeError | null, response?: {} | null): void; + (err: FakeError|null, response?: {} | null): void; } -export class Operation { - constructor() {} - promise() {} +export class Operation{ + constructor(){}; + promise() {}; } -function mockLongRunningGrpcMethod( - expectedRequest: {}, - response: {} | null, - error?: {} | null -) { - return (request: {}) => { - assert.deepStrictEqual(request, expectedRequest); - const mockOperation = { - promise() { - return new Promise((resolve, reject) => { - if (error) { - reject(error); - } else { - resolve([response]); +function mockLongRunningGrpcMethod(expectedRequest: {}, response: {} | null, error?: {} | null) { + return (request: {}) => { + assert.deepStrictEqual(request, expectedRequest); + const mockOperation = { + promise: function() { + return new Promise((resolve, reject) => { + if (error) { + reject(error); + } + else { + resolve([response]); + } + }); } - }); - }, + }; + return Promise.resolve([mockOperation]); }; - return Promise.resolve([mockOperation]); - }; } describe('v1.VideoIntelligenceServiceClient', () => { - it('has servicePath', () => { - const servicePath = - videointelligenceserviceModule.v1.VideoIntelligenceServiceClient - .servicePath; - assert(servicePath); - }); - it('has apiEndpoint', () => { - const apiEndpoint = - videointelligenceserviceModule.v1.VideoIntelligenceServiceClient - .apiEndpoint; - assert(apiEndpoint); - }); - it('has port', () => { - const port = - videointelligenceserviceModule.v1.VideoIntelligenceServiceClient.port; - assert(port); - assert(typeof port === 'number'); - }); - it('should create a client with no option', () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient(); - assert(client); - }); - it('should create a client with gRPC fallback', () => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient( - { - fallback: true, - } - ); - assert(client); - }); - describe('annotateVideo', () => { - it('invokes annotateVideo without error', done => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient( - { - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - } - ); - // Mock request - const request: protosTypes.google.cloud.videointelligence.v1.IAnnotateVideoRequest = {}; - // Mock response - const expectedResponse = {}; - // Mock gRPC layer - client._innerApiCalls.annotateVideo = mockLongRunningGrpcMethod( - request, - expectedResponse - ); - client - .annotateVideo(request) - .then((responses: [Operation]) => { - const operation = responses[0]; - return operation ? operation.promise() : {}; - }) - .then((responses: [Operation]) => { - assert.deepStrictEqual(responses[0], expectedResponse); - done(); - }) - .catch((err: {}) => { - done(err); + it('has servicePath', () => { + const servicePath = videointelligenceserviceModule.v1.VideoIntelligenceServiceClient.servicePath; + assert(servicePath); + }); + it('has apiEndpoint', () => { + const apiEndpoint = videointelligenceserviceModule.v1.VideoIntelligenceServiceClient.apiEndpoint; + assert(apiEndpoint); + }); + it('has port', () => { + const port = videointelligenceserviceModule.v1.VideoIntelligenceServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); + it('should create a client with no option', () => { + const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient(); + assert(client); + }); + it('should create a client with gRPC fallback', () => { + const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + fallback: true, }); + assert(client); }); + it('has initialize method and supports deferred initialization', async () => { + const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.videoIntelligenceServiceStub, undefined); + await client.initialize(); + assert(client.videoIntelligenceServiceStub); + }); + it('has close method', () => { + const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.close(); + }); + describe('annotateVideo', () => { + it('invokes annotateVideo without error', done => { + const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + // Initialize client before mocking + client.initialize(); + // Mock request + const request: protosTypes.google.cloud.videointelligence.v1.IAnnotateVideoRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock gRPC layer + client._innerApiCalls.annotateVideo = mockLongRunningGrpcMethod( + request, + expectedResponse + ); + client.annotateVideo(request).then((responses: [Operation]) => { + const operation = responses[0]; + return operation? operation.promise() : {}; + }).then((responses: [Operation]) => { + assert.deepStrictEqual(responses[0], expectedResponse); + done(); + }).catch((err: {}) => { + done(err); + }); + }); - it('invokes annotateVideo with error', done => { - const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient( - { - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - } - ); - // Mock request - const request: protosTypes.google.cloud.videointelligence.v1.IAnnotateVideoRequest = {}; - // Mock response - const expectedResponse = {}; - // Mock gRPC layer - client._innerApiCalls.annotateVideo = mockLongRunningGrpcMethod( - request, - null, - error - ); - client - .annotateVideo(request) - .then((responses: [Operation]) => { - const operation = responses[0]; - return operation ? operation.promise() : {}; - }) - .then(() => { - assert.fail(); - }) - .catch((err: FakeError) => { - assert(err instanceof FakeError); - assert.strictEqual(err.code, FAKE_STATUS_CODE); - done(); + it('invokes annotateVideo with error', done => { + const client = new videointelligenceserviceModule.v1.VideoIntelligenceServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + // Initialize client before mocking + client.initialize(); + // Mock request + const request: protosTypes.google.cloud.videointelligence.v1.IAnnotateVideoRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock gRPC layer + client._innerApiCalls.annotateVideo = mockLongRunningGrpcMethod( + request, + null, + error + ); + client.annotateVideo(request).then((responses: [Operation]) => { + const operation = responses[0]; + return operation? operation.promise() : {}; + }).then(() => { + assert.fail(); + }).catch((err: FakeError) => { + assert(err instanceof FakeError); + assert.strictEqual(err.code, FAKE_STATUS_CODE); + done(); + }); }); }); - }); }); diff --git a/test/gapic-video_intelligence_service-v1beta2.ts b/test/gapic-video_intelligence_service-v1beta2.ts index 136b9373..ac78ed70 100644 --- a/test/gapic-video_intelligence_service-v1beta2.ts +++ b/test/gapic-video_intelligence_service-v1beta2.ts @@ -18,145 +18,143 @@ import * as protosTypes from '../protos/protos'; import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import { describe, it } from 'mocha'; const videointelligenceserviceModule = require('../src'); + const FAKE_STATUS_CODE = 1; -class FakeError { - name: string; - message: string; - code: number; - constructor(n: number) { - this.name = 'fakeName'; - this.message = 'fake message'; - this.code = n; - } +class FakeError{ + name: string; + message: string; + code: number; + constructor(n: number){ + this.name = 'fakeName'; + this.message = 'fake message'; + this.code = n; + } } const error = new FakeError(FAKE_STATUS_CODE); export interface Callback { - (err: FakeError | null, response?: {} | null): void; + (err: FakeError|null, response?: {} | null): void; } -export class Operation { - constructor() {} - promise() {} +export class Operation{ + constructor(){}; + promise() {}; } -function mockLongRunningGrpcMethod( - expectedRequest: {}, - response: {} | null, - error?: {} | null -) { - return (request: {}) => { - assert.deepStrictEqual(request, expectedRequest); - const mockOperation = { - promise() { - return new Promise((resolve, reject) => { - if (error) { - reject(error); - } else { - resolve([response]); +function mockLongRunningGrpcMethod(expectedRequest: {}, response: {} | null, error?: {} | null) { + return (request: {}) => { + assert.deepStrictEqual(request, expectedRequest); + const mockOperation = { + promise: function() { + return new Promise((resolve, reject) => { + if (error) { + reject(error); + } + else { + resolve([response]); + } + }); } - }); - }, + }; + return Promise.resolve([mockOperation]); }; - return Promise.resolve([mockOperation]); - }; } describe('v1beta2.VideoIntelligenceServiceClient', () => { - it('has servicePath', () => { - const servicePath = - videointelligenceserviceModule.v1beta2.VideoIntelligenceServiceClient - .servicePath; - assert(servicePath); - }); - it('has apiEndpoint', () => { - const apiEndpoint = - videointelligenceserviceModule.v1beta2.VideoIntelligenceServiceClient - .apiEndpoint; - assert(apiEndpoint); - }); - it('has port', () => { - const port = - videointelligenceserviceModule.v1beta2.VideoIntelligenceServiceClient - .port; - assert(port); - assert(typeof port === 'number'); - }); - it('should create a client with no option', () => { - const client = new videointelligenceserviceModule.v1beta2.VideoIntelligenceServiceClient(); - assert(client); - }); - it('should create a client with gRPC fallback', () => { - const client = new videointelligenceserviceModule.v1beta2.VideoIntelligenceServiceClient( - { - fallback: true, - } - ); - assert(client); - }); - describe('annotateVideo', () => { - it('invokes annotateVideo without error', done => { - const client = new videointelligenceserviceModule.v1beta2.VideoIntelligenceServiceClient( - { - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - } - ); - // Mock request - const request: protosTypes.google.cloud.videointelligence.v1beta2.IAnnotateVideoRequest = {}; - // Mock response - const expectedResponse = {}; - // Mock gRPC layer - client._innerApiCalls.annotateVideo = mockLongRunningGrpcMethod( - request, - expectedResponse - ); - client - .annotateVideo(request) - .then((responses: [Operation]) => { - const operation = responses[0]; - return operation ? operation.promise() : {}; - }) - .then((responses: [Operation]) => { - assert.deepStrictEqual(responses[0], expectedResponse); - done(); - }) - .catch((err: {}) => { - done(err); + it('has servicePath', () => { + const servicePath = videointelligenceserviceModule.v1beta2.VideoIntelligenceServiceClient.servicePath; + assert(servicePath); + }); + it('has apiEndpoint', () => { + const apiEndpoint = videointelligenceserviceModule.v1beta2.VideoIntelligenceServiceClient.apiEndpoint; + assert(apiEndpoint); + }); + it('has port', () => { + const port = videointelligenceserviceModule.v1beta2.VideoIntelligenceServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); + it('should create a client with no option', () => { + const client = new videointelligenceserviceModule.v1beta2.VideoIntelligenceServiceClient(); + assert(client); + }); + it('should create a client with gRPC fallback', () => { + const client = new videointelligenceserviceModule.v1beta2.VideoIntelligenceServiceClient({ + fallback: true, }); + assert(client); }); + it('has initialize method and supports deferred initialization', async () => { + const client = new videointelligenceserviceModule.v1beta2.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.videoIntelligenceServiceStub, undefined); + await client.initialize(); + assert(client.videoIntelligenceServiceStub); + }); + it('has close method', () => { + const client = new videointelligenceserviceModule.v1beta2.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.close(); + }); + describe('annotateVideo', () => { + it('invokes annotateVideo without error', done => { + const client = new videointelligenceserviceModule.v1beta2.VideoIntelligenceServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + // Initialize client before mocking + client.initialize(); + // Mock request + const request: protosTypes.google.cloud.videointelligence.v1beta2.IAnnotateVideoRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock gRPC layer + client._innerApiCalls.annotateVideo = mockLongRunningGrpcMethod( + request, + expectedResponse + ); + client.annotateVideo(request).then((responses: [Operation]) => { + const operation = responses[0]; + return operation? operation.promise() : {}; + }).then((responses: [Operation]) => { + assert.deepStrictEqual(responses[0], expectedResponse); + done(); + }).catch((err: {}) => { + done(err); + }); + }); - it('invokes annotateVideo with error', done => { - const client = new videointelligenceserviceModule.v1beta2.VideoIntelligenceServiceClient( - { - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - } - ); - // Mock request - const request: protosTypes.google.cloud.videointelligence.v1beta2.IAnnotateVideoRequest = {}; - // Mock response - const expectedResponse = {}; - // Mock gRPC layer - client._innerApiCalls.annotateVideo = mockLongRunningGrpcMethod( - request, - null, - error - ); - client - .annotateVideo(request) - .then((responses: [Operation]) => { - const operation = responses[0]; - return operation ? operation.promise() : {}; - }) - .then(() => { - assert.fail(); - }) - .catch((err: FakeError) => { - assert(err instanceof FakeError); - assert.strictEqual(err.code, FAKE_STATUS_CODE); - done(); + it('invokes annotateVideo with error', done => { + const client = new videointelligenceserviceModule.v1beta2.VideoIntelligenceServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + // Initialize client before mocking + client.initialize(); + // Mock request + const request: protosTypes.google.cloud.videointelligence.v1beta2.IAnnotateVideoRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock gRPC layer + client._innerApiCalls.annotateVideo = mockLongRunningGrpcMethod( + request, + null, + error + ); + client.annotateVideo(request).then((responses: [Operation]) => { + const operation = responses[0]; + return operation? operation.promise() : {}; + }).then(() => { + assert.fail(); + }).catch((err: FakeError) => { + assert(err instanceof FakeError); + assert.strictEqual(err.code, FAKE_STATUS_CODE); + done(); + }); }); }); - }); }); diff --git a/test/gapic-video_intelligence_service-v1p1beta1.ts b/test/gapic-video_intelligence_service-v1p1beta1.ts index cb41aaba..e6b4abbd 100644 --- a/test/gapic-video_intelligence_service-v1p1beta1.ts +++ b/test/gapic-video_intelligence_service-v1p1beta1.ts @@ -18,145 +18,143 @@ import * as protosTypes from '../protos/protos'; import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import { describe, it } from 'mocha'; const videointelligenceserviceModule = require('../src'); + const FAKE_STATUS_CODE = 1; -class FakeError { - name: string; - message: string; - code: number; - constructor(n: number) { - this.name = 'fakeName'; - this.message = 'fake message'; - this.code = n; - } +class FakeError{ + name: string; + message: string; + code: number; + constructor(n: number){ + this.name = 'fakeName'; + this.message = 'fake message'; + this.code = n; + } } const error = new FakeError(FAKE_STATUS_CODE); export interface Callback { - (err: FakeError | null, response?: {} | null): void; + (err: FakeError|null, response?: {} | null): void; } -export class Operation { - constructor() {} - promise() {} +export class Operation{ + constructor(){}; + promise() {}; } -function mockLongRunningGrpcMethod( - expectedRequest: {}, - response: {} | null, - error?: {} | null -) { - return (request: {}) => { - assert.deepStrictEqual(request, expectedRequest); - const mockOperation = { - promise() { - return new Promise((resolve, reject) => { - if (error) { - reject(error); - } else { - resolve([response]); +function mockLongRunningGrpcMethod(expectedRequest: {}, response: {} | null, error?: {} | null) { + return (request: {}) => { + assert.deepStrictEqual(request, expectedRequest); + const mockOperation = { + promise: function() { + return new Promise((resolve, reject) => { + if (error) { + reject(error); + } + else { + resolve([response]); + } + }); } - }); - }, + }; + return Promise.resolve([mockOperation]); }; - return Promise.resolve([mockOperation]); - }; } describe('v1p1beta1.VideoIntelligenceServiceClient', () => { - it('has servicePath', () => { - const servicePath = - videointelligenceserviceModule.v1p1beta1.VideoIntelligenceServiceClient - .servicePath; - assert(servicePath); - }); - it('has apiEndpoint', () => { - const apiEndpoint = - videointelligenceserviceModule.v1p1beta1.VideoIntelligenceServiceClient - .apiEndpoint; - assert(apiEndpoint); - }); - it('has port', () => { - const port = - videointelligenceserviceModule.v1p1beta1.VideoIntelligenceServiceClient - .port; - assert(port); - assert(typeof port === 'number'); - }); - it('should create a client with no option', () => { - const client = new videointelligenceserviceModule.v1p1beta1.VideoIntelligenceServiceClient(); - assert(client); - }); - it('should create a client with gRPC fallback', () => { - const client = new videointelligenceserviceModule.v1p1beta1.VideoIntelligenceServiceClient( - { - fallback: true, - } - ); - assert(client); - }); - describe('annotateVideo', () => { - it('invokes annotateVideo without error', done => { - const client = new videointelligenceserviceModule.v1p1beta1.VideoIntelligenceServiceClient( - { - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - } - ); - // Mock request - const request: protosTypes.google.cloud.videointelligence.v1p1beta1.IAnnotateVideoRequest = {}; - // Mock response - const expectedResponse = {}; - // Mock gRPC layer - client._innerApiCalls.annotateVideo = mockLongRunningGrpcMethod( - request, - expectedResponse - ); - client - .annotateVideo(request) - .then((responses: [Operation]) => { - const operation = responses[0]; - return operation ? operation.promise() : {}; - }) - .then((responses: [Operation]) => { - assert.deepStrictEqual(responses[0], expectedResponse); - done(); - }) - .catch((err: {}) => { - done(err); + it('has servicePath', () => { + const servicePath = videointelligenceserviceModule.v1p1beta1.VideoIntelligenceServiceClient.servicePath; + assert(servicePath); + }); + it('has apiEndpoint', () => { + const apiEndpoint = videointelligenceserviceModule.v1p1beta1.VideoIntelligenceServiceClient.apiEndpoint; + assert(apiEndpoint); + }); + it('has port', () => { + const port = videointelligenceserviceModule.v1p1beta1.VideoIntelligenceServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); + it('should create a client with no option', () => { + const client = new videointelligenceserviceModule.v1p1beta1.VideoIntelligenceServiceClient(); + assert(client); + }); + it('should create a client with gRPC fallback', () => { + const client = new videointelligenceserviceModule.v1p1beta1.VideoIntelligenceServiceClient({ + fallback: true, }); + assert(client); }); + it('has initialize method and supports deferred initialization', async () => { + const client = new videointelligenceserviceModule.v1p1beta1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.videoIntelligenceServiceStub, undefined); + await client.initialize(); + assert(client.videoIntelligenceServiceStub); + }); + it('has close method', () => { + const client = new videointelligenceserviceModule.v1p1beta1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.close(); + }); + describe('annotateVideo', () => { + it('invokes annotateVideo without error', done => { + const client = new videointelligenceserviceModule.v1p1beta1.VideoIntelligenceServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + // Initialize client before mocking + client.initialize(); + // Mock request + const request: protosTypes.google.cloud.videointelligence.v1p1beta1.IAnnotateVideoRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock gRPC layer + client._innerApiCalls.annotateVideo = mockLongRunningGrpcMethod( + request, + expectedResponse + ); + client.annotateVideo(request).then((responses: [Operation]) => { + const operation = responses[0]; + return operation? operation.promise() : {}; + }).then((responses: [Operation]) => { + assert.deepStrictEqual(responses[0], expectedResponse); + done(); + }).catch((err: {}) => { + done(err); + }); + }); - it('invokes annotateVideo with error', done => { - const client = new videointelligenceserviceModule.v1p1beta1.VideoIntelligenceServiceClient( - { - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - } - ); - // Mock request - const request: protosTypes.google.cloud.videointelligence.v1p1beta1.IAnnotateVideoRequest = {}; - // Mock response - const expectedResponse = {}; - // Mock gRPC layer - client._innerApiCalls.annotateVideo = mockLongRunningGrpcMethod( - request, - null, - error - ); - client - .annotateVideo(request) - .then((responses: [Operation]) => { - const operation = responses[0]; - return operation ? operation.promise() : {}; - }) - .then(() => { - assert.fail(); - }) - .catch((err: FakeError) => { - assert(err instanceof FakeError); - assert.strictEqual(err.code, FAKE_STATUS_CODE); - done(); + it('invokes annotateVideo with error', done => { + const client = new videointelligenceserviceModule.v1p1beta1.VideoIntelligenceServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + // Initialize client before mocking + client.initialize(); + // Mock request + const request: protosTypes.google.cloud.videointelligence.v1p1beta1.IAnnotateVideoRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock gRPC layer + client._innerApiCalls.annotateVideo = mockLongRunningGrpcMethod( + request, + null, + error + ); + client.annotateVideo(request).then((responses: [Operation]) => { + const operation = responses[0]; + return operation? operation.promise() : {}; + }).then(() => { + assert.fail(); + }).catch((err: FakeError) => { + assert(err instanceof FakeError); + assert.strictEqual(err.code, FAKE_STATUS_CODE); + done(); + }); }); }); - }); }); diff --git a/test/gapic-video_intelligence_service-v1p2beta1.ts b/test/gapic-video_intelligence_service-v1p2beta1.ts index 55389367..2ab7dabc 100644 --- a/test/gapic-video_intelligence_service-v1p2beta1.ts +++ b/test/gapic-video_intelligence_service-v1p2beta1.ts @@ -18,145 +18,143 @@ import * as protosTypes from '../protos/protos'; import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import { describe, it } from 'mocha'; const videointelligenceserviceModule = require('../src'); + const FAKE_STATUS_CODE = 1; -class FakeError { - name: string; - message: string; - code: number; - constructor(n: number) { - this.name = 'fakeName'; - this.message = 'fake message'; - this.code = n; - } +class FakeError{ + name: string; + message: string; + code: number; + constructor(n: number){ + this.name = 'fakeName'; + this.message = 'fake message'; + this.code = n; + } } const error = new FakeError(FAKE_STATUS_CODE); export interface Callback { - (err: FakeError | null, response?: {} | null): void; + (err: FakeError|null, response?: {} | null): void; } -export class Operation { - constructor() {} - promise() {} +export class Operation{ + constructor(){}; + promise() {}; } -function mockLongRunningGrpcMethod( - expectedRequest: {}, - response: {} | null, - error?: {} | null -) { - return (request: {}) => { - assert.deepStrictEqual(request, expectedRequest); - const mockOperation = { - promise() { - return new Promise((resolve, reject) => { - if (error) { - reject(error); - } else { - resolve([response]); +function mockLongRunningGrpcMethod(expectedRequest: {}, response: {} | null, error?: {} | null) { + return (request: {}) => { + assert.deepStrictEqual(request, expectedRequest); + const mockOperation = { + promise: function() { + return new Promise((resolve, reject) => { + if (error) { + reject(error); + } + else { + resolve([response]); + } + }); } - }); - }, + }; + return Promise.resolve([mockOperation]); }; - return Promise.resolve([mockOperation]); - }; } describe('v1p2beta1.VideoIntelligenceServiceClient', () => { - it('has servicePath', () => { - const servicePath = - videointelligenceserviceModule.v1p2beta1.VideoIntelligenceServiceClient - .servicePath; - assert(servicePath); - }); - it('has apiEndpoint', () => { - const apiEndpoint = - videointelligenceserviceModule.v1p2beta1.VideoIntelligenceServiceClient - .apiEndpoint; - assert(apiEndpoint); - }); - it('has port', () => { - const port = - videointelligenceserviceModule.v1p2beta1.VideoIntelligenceServiceClient - .port; - assert(port); - assert(typeof port === 'number'); - }); - it('should create a client with no option', () => { - const client = new videointelligenceserviceModule.v1p2beta1.VideoIntelligenceServiceClient(); - assert(client); - }); - it('should create a client with gRPC fallback', () => { - const client = new videointelligenceserviceModule.v1p2beta1.VideoIntelligenceServiceClient( - { - fallback: true, - } - ); - assert(client); - }); - describe('annotateVideo', () => { - it('invokes annotateVideo without error', done => { - const client = new videointelligenceserviceModule.v1p2beta1.VideoIntelligenceServiceClient( - { - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - } - ); - // Mock request - const request: protosTypes.google.cloud.videointelligence.v1p2beta1.IAnnotateVideoRequest = {}; - // Mock response - const expectedResponse = {}; - // Mock gRPC layer - client._innerApiCalls.annotateVideo = mockLongRunningGrpcMethod( - request, - expectedResponse - ); - client - .annotateVideo(request) - .then((responses: [Operation]) => { - const operation = responses[0]; - return operation ? operation.promise() : {}; - }) - .then((responses: [Operation]) => { - assert.deepStrictEqual(responses[0], expectedResponse); - done(); - }) - .catch((err: {}) => { - done(err); + it('has servicePath', () => { + const servicePath = videointelligenceserviceModule.v1p2beta1.VideoIntelligenceServiceClient.servicePath; + assert(servicePath); + }); + it('has apiEndpoint', () => { + const apiEndpoint = videointelligenceserviceModule.v1p2beta1.VideoIntelligenceServiceClient.apiEndpoint; + assert(apiEndpoint); + }); + it('has port', () => { + const port = videointelligenceserviceModule.v1p2beta1.VideoIntelligenceServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); + it('should create a client with no option', () => { + const client = new videointelligenceserviceModule.v1p2beta1.VideoIntelligenceServiceClient(); + assert(client); + }); + it('should create a client with gRPC fallback', () => { + const client = new videointelligenceserviceModule.v1p2beta1.VideoIntelligenceServiceClient({ + fallback: true, }); + assert(client); }); + it('has initialize method and supports deferred initialization', async () => { + const client = new videointelligenceserviceModule.v1p2beta1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.videoIntelligenceServiceStub, undefined); + await client.initialize(); + assert(client.videoIntelligenceServiceStub); + }); + it('has close method', () => { + const client = new videointelligenceserviceModule.v1p2beta1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.close(); + }); + describe('annotateVideo', () => { + it('invokes annotateVideo without error', done => { + const client = new videointelligenceserviceModule.v1p2beta1.VideoIntelligenceServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + // Initialize client before mocking + client.initialize(); + // Mock request + const request: protosTypes.google.cloud.videointelligence.v1p2beta1.IAnnotateVideoRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock gRPC layer + client._innerApiCalls.annotateVideo = mockLongRunningGrpcMethod( + request, + expectedResponse + ); + client.annotateVideo(request).then((responses: [Operation]) => { + const operation = responses[0]; + return operation? operation.promise() : {}; + }).then((responses: [Operation]) => { + assert.deepStrictEqual(responses[0], expectedResponse); + done(); + }).catch((err: {}) => { + done(err); + }); + }); - it('invokes annotateVideo with error', done => { - const client = new videointelligenceserviceModule.v1p2beta1.VideoIntelligenceServiceClient( - { - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - } - ); - // Mock request - const request: protosTypes.google.cloud.videointelligence.v1p2beta1.IAnnotateVideoRequest = {}; - // Mock response - const expectedResponse = {}; - // Mock gRPC layer - client._innerApiCalls.annotateVideo = mockLongRunningGrpcMethod( - request, - null, - error - ); - client - .annotateVideo(request) - .then((responses: [Operation]) => { - const operation = responses[0]; - return operation ? operation.promise() : {}; - }) - .then(() => { - assert.fail(); - }) - .catch((err: FakeError) => { - assert(err instanceof FakeError); - assert.strictEqual(err.code, FAKE_STATUS_CODE); - done(); + it('invokes annotateVideo with error', done => { + const client = new videointelligenceserviceModule.v1p2beta1.VideoIntelligenceServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + // Initialize client before mocking + client.initialize(); + // Mock request + const request: protosTypes.google.cloud.videointelligence.v1p2beta1.IAnnotateVideoRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock gRPC layer + client._innerApiCalls.annotateVideo = mockLongRunningGrpcMethod( + request, + null, + error + ); + client.annotateVideo(request).then((responses: [Operation]) => { + const operation = responses[0]; + return operation? operation.promise() : {}; + }).then(() => { + assert.fail(); + }).catch((err: FakeError) => { + assert(err instanceof FakeError); + assert.strictEqual(err.code, FAKE_STATUS_CODE); + done(); + }); }); }); - }); }); diff --git a/test/gapic-video_intelligence_service-v1p3beta1.ts b/test/gapic-video_intelligence_service-v1p3beta1.ts index 9d4acfc7..fa9c7fb5 100644 --- a/test/gapic-video_intelligence_service-v1p3beta1.ts +++ b/test/gapic-video_intelligence_service-v1p3beta1.ts @@ -18,145 +18,143 @@ import * as protosTypes from '../protos/protos'; import * as assert from 'assert'; -import {describe, it} from 'mocha'; +import { describe, it } from 'mocha'; const videointelligenceserviceModule = require('../src'); + const FAKE_STATUS_CODE = 1; -class FakeError { - name: string; - message: string; - code: number; - constructor(n: number) { - this.name = 'fakeName'; - this.message = 'fake message'; - this.code = n; - } +class FakeError{ + name: string; + message: string; + code: number; + constructor(n: number){ + this.name = 'fakeName'; + this.message = 'fake message'; + this.code = n; + } } const error = new FakeError(FAKE_STATUS_CODE); export interface Callback { - (err: FakeError | null, response?: {} | null): void; + (err: FakeError|null, response?: {} | null): void; } -export class Operation { - constructor() {} - promise() {} +export class Operation{ + constructor(){}; + promise() {}; } -function mockLongRunningGrpcMethod( - expectedRequest: {}, - response: {} | null, - error?: {} | null -) { - return (request: {}) => { - assert.deepStrictEqual(request, expectedRequest); - const mockOperation = { - promise() { - return new Promise((resolve, reject) => { - if (error) { - reject(error); - } else { - resolve([response]); +function mockLongRunningGrpcMethod(expectedRequest: {}, response: {} | null, error?: {} | null) { + return (request: {}) => { + assert.deepStrictEqual(request, expectedRequest); + const mockOperation = { + promise: function() { + return new Promise((resolve, reject) => { + if (error) { + reject(error); + } + else { + resolve([response]); + } + }); } - }); - }, + }; + return Promise.resolve([mockOperation]); }; - return Promise.resolve([mockOperation]); - }; } describe('v1p3beta1.VideoIntelligenceServiceClient', () => { - it('has servicePath', () => { - const servicePath = - videointelligenceserviceModule.v1p3beta1.VideoIntelligenceServiceClient - .servicePath; - assert(servicePath); - }); - it('has apiEndpoint', () => { - const apiEndpoint = - videointelligenceserviceModule.v1p3beta1.VideoIntelligenceServiceClient - .apiEndpoint; - assert(apiEndpoint); - }); - it('has port', () => { - const port = - videointelligenceserviceModule.v1p3beta1.VideoIntelligenceServiceClient - .port; - assert(port); - assert(typeof port === 'number'); - }); - it('should create a client with no option', () => { - const client = new videointelligenceserviceModule.v1p3beta1.VideoIntelligenceServiceClient(); - assert(client); - }); - it('should create a client with gRPC fallback', () => { - const client = new videointelligenceserviceModule.v1p3beta1.VideoIntelligenceServiceClient( - { - fallback: true, - } - ); - assert(client); - }); - describe('annotateVideo', () => { - it('invokes annotateVideo without error', done => { - const client = new videointelligenceserviceModule.v1p3beta1.VideoIntelligenceServiceClient( - { - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - } - ); - // Mock request - const request: protosTypes.google.cloud.videointelligence.v1p3beta1.IAnnotateVideoRequest = {}; - // Mock response - const expectedResponse = {}; - // Mock gRPC layer - client._innerApiCalls.annotateVideo = mockLongRunningGrpcMethod( - request, - expectedResponse - ); - client - .annotateVideo(request) - .then((responses: [Operation]) => { - const operation = responses[0]; - return operation ? operation.promise() : {}; - }) - .then((responses: [Operation]) => { - assert.deepStrictEqual(responses[0], expectedResponse); - done(); - }) - .catch((err: {}) => { - done(err); + it('has servicePath', () => { + const servicePath = videointelligenceserviceModule.v1p3beta1.VideoIntelligenceServiceClient.servicePath; + assert(servicePath); + }); + it('has apiEndpoint', () => { + const apiEndpoint = videointelligenceserviceModule.v1p3beta1.VideoIntelligenceServiceClient.apiEndpoint; + assert(apiEndpoint); + }); + it('has port', () => { + const port = videointelligenceserviceModule.v1p3beta1.VideoIntelligenceServiceClient.port; + assert(port); + assert(typeof port === 'number'); + }); + it('should create a client with no option', () => { + const client = new videointelligenceserviceModule.v1p3beta1.VideoIntelligenceServiceClient(); + assert(client); + }); + it('should create a client with gRPC fallback', () => { + const client = new videointelligenceserviceModule.v1p3beta1.VideoIntelligenceServiceClient({ + fallback: true, }); + assert(client); }); + it('has initialize method and supports deferred initialization', async () => { + const client = new videointelligenceserviceModule.v1p3beta1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + assert.strictEqual(client.videoIntelligenceServiceStub, undefined); + await client.initialize(); + assert(client.videoIntelligenceServiceStub); + }); + it('has close method', () => { + const client = new videointelligenceserviceModule.v1p3beta1.VideoIntelligenceServiceClient({ + credentials: { client_email: 'bogus', private_key: 'bogus' }, + projectId: 'bogus', + }); + client.close(); + }); + describe('annotateVideo', () => { + it('invokes annotateVideo without error', done => { + const client = new videointelligenceserviceModule.v1p3beta1.VideoIntelligenceServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + // Initialize client before mocking + client.initialize(); + // Mock request + const request: protosTypes.google.cloud.videointelligence.v1p3beta1.IAnnotateVideoRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock gRPC layer + client._innerApiCalls.annotateVideo = mockLongRunningGrpcMethod( + request, + expectedResponse + ); + client.annotateVideo(request).then((responses: [Operation]) => { + const operation = responses[0]; + return operation? operation.promise() : {}; + }).then((responses: [Operation]) => { + assert.deepStrictEqual(responses[0], expectedResponse); + done(); + }).catch((err: {}) => { + done(err); + }); + }); - it('invokes annotateVideo with error', done => { - const client = new videointelligenceserviceModule.v1p3beta1.VideoIntelligenceServiceClient( - { - credentials: {client_email: 'bogus', private_key: 'bogus'}, - projectId: 'bogus', - } - ); - // Mock request - const request: protosTypes.google.cloud.videointelligence.v1p3beta1.IAnnotateVideoRequest = {}; - // Mock response - const expectedResponse = {}; - // Mock gRPC layer - client._innerApiCalls.annotateVideo = mockLongRunningGrpcMethod( - request, - null, - error - ); - client - .annotateVideo(request) - .then((responses: [Operation]) => { - const operation = responses[0]; - return operation ? operation.promise() : {}; - }) - .then(() => { - assert.fail(); - }) - .catch((err: FakeError) => { - assert(err instanceof FakeError); - assert.strictEqual(err.code, FAKE_STATUS_CODE); - done(); + it('invokes annotateVideo with error', done => { + const client = new videointelligenceserviceModule.v1p3beta1.VideoIntelligenceServiceClient({ + credentials: {client_email: 'bogus', private_key: 'bogus'}, + projectId: 'bogus', + }); + // Initialize client before mocking + client.initialize(); + // Mock request + const request: protosTypes.google.cloud.videointelligence.v1p3beta1.IAnnotateVideoRequest = {}; + // Mock response + const expectedResponse = {}; + // Mock gRPC layer + client._innerApiCalls.annotateVideo = mockLongRunningGrpcMethod( + request, + null, + error + ); + client.annotateVideo(request).then((responses: [Operation]) => { + const operation = responses[0]; + return operation? operation.promise() : {}; + }).then(() => { + assert.fail(); + }).catch((err: FakeError) => { + assert(err instanceof FakeError); + assert.strictEqual(err.code, FAKE_STATUS_CODE); + done(); + }); }); }); - }); });