File

src/operation.ts

Extends

GrpcServiceObject

Index

Properties
Methods

Constructor

constructor(parent: GrpcService | GrpcServiceObject, name: string)

An Operation object allows you to interact with APIs that take longer to process things.

Parameters :
Name Type Optional Description
parent GrpcService | GrpcServiceObject No
name string No
  • The operation name.

Properties

completeListeners
Type : number
hasActiveListeners
Type : boolean
parent
Type : GrpcServiceObject
Inherited from GrpcServiceObject

Methods

cancel
cancel(callback: (err: Error | null,apiResponse: Response) => void)

Cancel the operation.

Parameters :
Name Type Optional Description
callback function No
  • The callback function.
Returns : void
delete
delete()
Inherited from GrpcServiceObject

Delete the object.

Returns : Promise<>
delete
delete(callback?: RequestCallback)
Inherited from GrpcServiceObject
Parameters :
Name Type Optional
callback RequestCallback Yes
Returns : void | Promise
delete
delete(callback: RequestCallback)
Inherited from GrpcServiceObject
Parameters :
Name Type Optional
callback RequestCallback No
Returns : void
getMetadata
getMetadata()
Inherited from GrpcServiceObject

Get the metadata of this object.

Returns : Promise<Metadata>
getMetadata
getMetadata(callback: MetadataCallback)
Inherited from GrpcServiceObject
Parameters :
Name Type Optional
callback MetadataCallback No
Returns : void
getMetadata
getMetadata(callback?: MetadataCallback)
Inherited from GrpcServiceObject
Parameters :
Name Type Optional
callback MetadataCallback Yes
Returns : void | Promise
request
request(...args: Array)
Inherited from GrpcServiceObject

Patch a request to the GrpcService object.

Parameters :
Name Type Optional
args Array<literal type> No
Returns : any
requestStream
requestStream(...args: Array)
Inherited from GrpcServiceObject

Patch a streaming request to the GrpcService object.

Parameters :
Name Type Optional
args Array<literal type> No
Returns : any
requestWritableStream
requestWritableStream(...args: Array)
Inherited from GrpcServiceObject

Patch a writable streaming request to the GrpcService object.

Parameters :
Name Type Optional
args Array<literal type> No
Returns : any
setMetadata
setMetadata(metadata: Metadata, callback?: ResponseCallback)
Inherited from GrpcServiceObject
Parameters :
Name Type Optional
metadata Metadata No
callback ResponseCallback Yes
Returns : void | Promise
setMetadata
setMetadata(metadata: Metadata, callback: ResponseCallback)
Inherited from GrpcServiceObject
Parameters :
Name Type Optional
metadata Metadata No
callback ResponseCallback No
Returns : void
setMetadata
setMetadata(metadata: Metadata)
Inherited from GrpcServiceObject

Set the metadata for this object.

Parameters :
Name Type Optional Description
metadata Metadata No
  • The metadata to set on this object.
Returns : Promise<SetMetadataResponse>
import {Metadata, ServiceObjectConfig, util} from '@google-cloud/common';
import {Response} from 'teeny-request';

/**
 * @type {module:commonGrpc/service}
 * @private
 */
import {GrpcService} from './service';
/**
 * @type {module:commonGrpc/serviceObject}
 * @private
 */
import {GrpcServiceObject} from './service-object';

export class GrpcOperation extends GrpcServiceObject {
  completeListeners: number;
  hasActiveListeners: boolean;

  /**
   * An Operation object allows you to interact with APIs that take longer to
   * process things.
   *
   * @constructor
   * @alias module:common/grpcOperation
   *
   * @param {module:commonGrpc/service|module:commonGrpc/serviceObject} parent - The
   *     parent object. This should be configured to use the
   * longrunning.operation service.
   * @param {string} name - The operation name.
   */
  constructor(parent: GrpcService | GrpcServiceObject, name: string) {
    const methods = {
      /**
       * Deletes an operation.
       */
      delete: {
        protoOpts: {
          service: 'Operations',
          method: 'deleteOperation',
        },
        reqOpts: {
          name,
        },
      },

      /**
       * Checks to see if an operation exists.
       */
      exists: true,

      /**
       * Retrieves the operation.
       */
      get: true,

      /**
       * Retrieves metadata for the operation.
       */
      getMetadata: {
        protoOpts: {
          service: 'Operations',
          method: 'getOperation',
        },
        reqOpts: {
          name,
        },
      },
    };

    const config = {
      parent,
      id: name,
      methods,
    };

    super((config as {}) as ServiceObjectConfig);
    this.completeListeners = 0;
    this.hasActiveListeners = false;
    this.listenForEvents_();
  }

  /**
   * Cancel the operation.
   *
   * @param {function=} callback - The callback function.
   * @param {?error} callback.err - An error returned while making this
   *     request.
   * @param {object} callback.apiResponse - The full API response.
   */
  cancel(callback: (err: Error | null, apiResponse?: Response) => void) {
    const protoOpts = {
      service: 'Operations',
      method: 'cancelOperation',
    };

    const reqOpts = {
      // TODO: remove this when upgrading to the latest @google-cloud/common
      name: this.id,
    };

    this.request(protoOpts, reqOpts, callback || util.noop);
  }

  /**
   * Poll for a status update. Execute the callback:
   *
   *   - callback(err): Operation failed
   *   - callback(): Operation incomplete
   *   - callback(null, metadata): Operation complete
   *
   * @private
   *
   * @param {function} callback
   */
  private poll_(): Promise<Metadata | null> {
    return new Promise((resolve, reject) => {
      this.getMetadata((err, resp) => {
        if (err || resp!.error) {
          reject(err || GrpcService.decorateError_(resp!.error));
          return;
        }
        if (!resp!.done) {
          resolve();
          return;
        }
        resolve(resp);
      });
    });
  }

  /**
   * Begin listening for events on the operation. This method keeps track of how
   * many "complete" listeners are registered and removed, making sure polling
   * is handled automatically.
   *
   * As long as there is one active "complete" listener, the connection is open.
   * When there are no more listeners, the polling stops.
   *
   * @private
   */
  protected listenForEvents_() {
    this.on('newListener', (event: string) => {
      if (event === 'complete') {
        this.completeListeners++;
        if (!this.hasActiveListeners) {
          this.hasActiveListeners = true;
          this.startPolling_();
        }
      }
    });

    this.on('removeListener', (event: string) => {
      if (event === 'complete' && --this.completeListeners === 0) {
        this.hasActiveListeners = false;
      }
    });
  }

  /**
   * Poll `getMetadata` to check the operation's status. This runs a loop to
   * ping the API on an interval.
   *
   * Note: This method is automatically called once a "complete" event handler
   * is registered on the operation.
   *
   * @private
   */
  protected async startPolling_() {
    if (!this.hasActiveListeners) {
      return;
    }
    try {
      const metadata = await this.poll_();
      if (!metadata) {
        setTimeout(this.startPolling_.bind(this), 500);
        return;
      }
      this.emit('complete', metadata);
    } catch (err) {
      this.emit('error', err);
    }
  }
}

result-matching ""

    No results matching ""