locationService.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. "use strict";
  2. // Copyright 2021 Google LLC
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // https://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. Object.defineProperty(exports, "__esModule", { value: true });
  16. exports.LocationsClient = void 0;
  17. /* global window */
  18. const gax = require("./gax");
  19. const warnings_1 = require("./warnings");
  20. const createApiCall_1 = require("./createApiCall");
  21. const routingHeader = require("./routingHeader");
  22. const pageDescriptor_1 = require("./paginationCalls/pageDescriptor");
  23. const jsonProtos = require("../protos/locations.json");
  24. /**
  25. * This file defines retry strategy and timeouts for all API methods in this library.
  26. */
  27. const gapicConfig = require("./locations_client_config.json");
  28. const version = require('../../package.json').version;
  29. /**
  30. * Google Cloud Locations Client.
  31. * This is manually written for providing methods [listLocations, getLocations] to the generated client.
  32. */
  33. class LocationsClient {
  34. /**
  35. * Construct an instance of LocationsClient.
  36. *
  37. * @param {object} [options] - The configuration object.
  38. * The options accepted by the constructor are described in detail
  39. * in [this document](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#creating-the-client-instance).
  40. * The common options are:
  41. * @param {object} [options.credentials] - Credentials object.
  42. * @param {string} [options.credentials.client_email]
  43. * @param {string} [options.credentials.private_key]
  44. * @param {string} [options.email] - Account email address. Required when
  45. * using a .pem or .p12 keyFilename.
  46. * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or
  47. * .p12 key downloaded from the Google Developers Console. If you provide
  48. * a path to a JSON file, the projectId option below is not necessary.
  49. * NOTE: .pem and .p12 require you to specify options.email as well.
  50. * @param {number} [options.port] - The port on which to connect to
  51. * the remote host.
  52. * @param {string} [options.projectId] - The project ID from the Google
  53. * Developer's Console, e.g. 'grape-spaceship-123'. We will also check
  54. * the environment variable GCLOUD_PROJECT for your project ID. If your
  55. * app is running in an environment which supports
  56. * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials},
  57. * your project ID will be detected automatically.
  58. * @param {string} [options.apiEndpoint] - The domain name of the
  59. * API remote host.
  60. * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override.
  61. * Follows the structure of {@link gapicConfig}.
  62. * @param {boolean} [options.fallback] - Use HTTP fallback mode.
  63. * In fallback mode, a special browser-compatible transport implementation is used
  64. * instead of gRPC transport. In browser context (if the `window` object is defined)
  65. * the fallback mode is enabled automatically; set `options.fallback` to `false`
  66. * if you need to override this behavior.
  67. */
  68. constructor(gaxGrpc,
  69. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  70. opts) {
  71. var _a, _b;
  72. this._terminated = false;
  73. this.descriptors = {
  74. page: {},
  75. stream: {},
  76. longrunning: {},
  77. batching: {},
  78. };
  79. // Ensure that options include all the required fields.
  80. this.gaxGrpc = gaxGrpc;
  81. const staticMembers = this.constructor;
  82. const servicePath = (opts === null || opts === void 0 ? void 0 : opts.servicePath) || (opts === null || opts === void 0 ? void 0 : opts.apiEndpoint) || staticMembers.servicePath;
  83. this._providedCustomServicePath = !!((opts === null || opts === void 0 ? void 0 : opts.servicePath) || (opts === null || opts === void 0 ? void 0 : opts.apiEndpoint));
  84. const port = (opts === null || opts === void 0 ? void 0 : opts.port) || staticMembers.port;
  85. const clientConfig = (_a = opts === null || opts === void 0 ? void 0 : opts.clientConfig) !== null && _a !== void 0 ? _a : {};
  86. const fallback = (_b = opts === null || opts === void 0 ? void 0 : opts.fallback) !== null && _b !== void 0 ? _b : (typeof window !== 'undefined' && typeof (window === null || window === void 0 ? void 0 : window.fetch) === 'function');
  87. opts = Object.assign({ servicePath, port, clientConfig, fallback }, opts);
  88. // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case.
  89. if (servicePath !== staticMembers.servicePath && !('scopes' in opts)) {
  90. opts['scopes'] = staticMembers.scopes;
  91. }
  92. // Save options to use in initialize() method.
  93. this._opts = opts;
  94. // Save the auth object to the client, for use by other methods.
  95. this.auth = gaxGrpc.auth;
  96. // Set the default scopes in auth client if needed.
  97. if (servicePath === staticMembers.servicePath) {
  98. this.auth.defaultScopes = staticMembers.scopes;
  99. }
  100. // Determine the client header string.
  101. const clientHeader = [`gax/${version}`, `gapic/${version}`];
  102. if (typeof process !== 'undefined' && 'versions' in process) {
  103. clientHeader.push(`gl-node/${process.versions.node}`);
  104. }
  105. else {
  106. clientHeader.push(`gl-web/${version}`);
  107. }
  108. if (!opts.fallback) {
  109. clientHeader.push(`grpc/${gaxGrpc.grpcVersion}`);
  110. }
  111. else if (opts.fallback === 'rest') {
  112. clientHeader.push(`rest/${gaxGrpc.grpcVersion}`);
  113. }
  114. if (opts.libName && opts.libVersion) {
  115. clientHeader.push(`${opts.libName}/${opts.libVersion}`);
  116. }
  117. // Load the applicable protos.
  118. this._protos = gaxGrpc.loadProtoJSON(jsonProtos);
  119. // Some of the methods on this service return "paged" results,
  120. // (e.g. 50 results at a time, with tokens to get subsequent
  121. // pages). Denote the keys used for pagination and results.
  122. this.descriptors.page = {
  123. listLocations: new pageDescriptor_1.PageDescriptor('pageToken', 'nextPageToken', 'locations'),
  124. };
  125. // Put together the default options sent with requests.
  126. this._defaults = gaxGrpc.constructSettings('google.cloud.location.Locations', gapicConfig, opts.clientConfig || {}, { 'x-goog-api-client': clientHeader.join(' ') });
  127. // Set up a dictionary of "inner API calls"; the core implementation
  128. // of calling the API is handled in `google-gax`, with this code
  129. // merely providing the destination and request information.
  130. this.innerApiCalls = {};
  131. // Add a warn function to the client constructor so it can be easily tested.
  132. this.warn = warnings_1.warn;
  133. }
  134. /**
  135. * Initialize the client.
  136. * Performs asynchronous operations (such as authentication) and prepares the client.
  137. * This function will be called automatically when any class method is called for the
  138. * first time, but if you need to initialize it before calling an actual method,
  139. * feel free to call initialize() directly.
  140. *
  141. * You can await on this method if you want to make sure the client is initialized.
  142. *
  143. * @returns {Promise} A promise that resolves to an authenticated service stub.
  144. */
  145. initialize() {
  146. // If the client stub promise is already initialized, return immediately.
  147. if (this.locationsStub) {
  148. return this.locationsStub;
  149. }
  150. // Put together the "service stub" for
  151. // google.cloud.location.Locations.
  152. this.locationsStub = this.gaxGrpc.createStub(this._opts.fallback
  153. ? this._protos.lookupService('google.cloud.location.Locations')
  154. : // eslint-disable-next-line @typescript-eslint/no-explicit-any
  155. this._protos.google.cloud.location.Locations, this._opts, this._providedCustomServicePath);
  156. // Iterate over each of the methods that the service provides
  157. // and create an API call method for each.
  158. const locationsStubMethods = ['listLocations', 'getLocation'];
  159. for (const methodName of locationsStubMethods) {
  160. const callPromise = this.locationsStub.then(stub => (...args) => {
  161. if (this._terminated) {
  162. return Promise.reject('The client has already been closed.');
  163. }
  164. const func = stub[methodName];
  165. return func.apply(stub, args);
  166. }, (err) => () => {
  167. throw err;
  168. });
  169. const descriptor = this.descriptors.page[methodName] || undefined;
  170. const apiCall = (0, createApiCall_1.createApiCall)(callPromise, this._defaults[methodName], descriptor);
  171. this.innerApiCalls[methodName] = apiCall;
  172. }
  173. return this.locationsStub;
  174. }
  175. /**
  176. * The DNS address for this API service.
  177. * @returns {string} The DNS address for this service.
  178. */
  179. static get servicePath() {
  180. return 'cloud.googleapis.com';
  181. }
  182. /**
  183. * The DNS address for this API service - same as servicePath(),
  184. * exists for compatibility reasons.
  185. * @returns {string} The DNS address for this service.
  186. */
  187. static get apiEndpoint() {
  188. return 'cloud.googleapis.com';
  189. }
  190. /**
  191. * The port for this API service.
  192. * @returns {number} The default port for this service.
  193. */
  194. static get port() {
  195. return 443;
  196. }
  197. /**
  198. * The scopes needed to make gRPC calls for every method defined
  199. * in this service.
  200. * @returns {string[]} List of default scopes.
  201. */
  202. static get scopes() {
  203. return ['https://www.googleapis.com/auth/cloud-platform'];
  204. }
  205. getProjectId(callback) {
  206. if (callback) {
  207. this.auth.getProjectId(callback);
  208. return;
  209. }
  210. return this.auth.getProjectId();
  211. }
  212. /**
  213. * Gets information about a location.
  214. *
  215. * @param {Object} request
  216. * The request object that will be sent.
  217. * @param {string} request.name
  218. * Resource name for the location.
  219. * @param {object} [options]
  220. * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
  221. * @returns {Promise} - The promise which resolves to an array.
  222. * The first element of the array is an object representing [Location]{@link google.cloud.location.Location}.
  223. * Please see the
  224. * [documentation](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#regular-methods)
  225. * for more details and examples.
  226. * @example
  227. * const [response] = await client.getLocation(request);
  228. */
  229. getLocation(request, optionsOrCallback, callback) {
  230. request = request || {};
  231. let options;
  232. if (typeof optionsOrCallback === 'function' && callback === undefined) {
  233. callback = optionsOrCallback;
  234. options = {};
  235. }
  236. else {
  237. options = optionsOrCallback;
  238. }
  239. options = options || {};
  240. options.otherArgs = options.otherArgs || {};
  241. options.otherArgs.headers = options.otherArgs.headers || {};
  242. options.otherArgs.headers['x-goog-request-params'] =
  243. routingHeader.fromParams({
  244. name: request.name || '',
  245. });
  246. this.initialize();
  247. return this.innerApiCalls.getLocation(request, options, callback);
  248. }
  249. /**
  250. * Lists information about the supported locations for this service.
  251. *
  252. * @param {Object} request
  253. * The request object that will be sent.
  254. * @param {string} request.name
  255. * The resource that owns the locations collection, if applicable.
  256. * @param {string} request.filter
  257. * The standard list filter.
  258. * @param {number} request.pageSize
  259. * The standard list page size.
  260. * @param {string} request.pageToken
  261. * The standard list page token.
  262. * @param {object} [options]
  263. * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
  264. * @returns {Promise} - The promise which resolves to an array.
  265. * The first element of the array is Array of [Location]{@link google.cloud.location.Location}.
  266. * The client library will perform auto-pagination by default: it will call the API as many
  267. * times as needed and will merge results from all the pages into this array.
  268. * Note that it can affect your quota.
  269. * We recommend using `listLocationsAsync()`
  270. * method described below for async iteration which you can stop as needed.
  271. * Please see the
  272. * [documentation](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#auto-pagination)
  273. * for more details and examples.
  274. */
  275. listLocations(request, optionsOrCallback, callback) {
  276. request = request || {};
  277. let options;
  278. if (typeof optionsOrCallback === 'function' && callback === undefined) {
  279. callback = optionsOrCallback;
  280. options = {};
  281. }
  282. else {
  283. options = optionsOrCallback;
  284. }
  285. options = options || {};
  286. options.otherArgs = options.otherArgs || {};
  287. options.otherArgs.headers = options.otherArgs.headers || {};
  288. options.otherArgs.headers['x-goog-request-params'] =
  289. routingHeader.fromParams({
  290. name: request.name || '',
  291. });
  292. this.initialize();
  293. return this.innerApiCalls.listLocations(request, options, callback);
  294. }
  295. /**
  296. * Equivalent to `listLocations`, but returns an iterable object.
  297. *
  298. * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand.
  299. * @param {Object} request
  300. * The request object that will be sent.
  301. * @param {string} request.name
  302. * The resource that owns the locations collection, if applicable.
  303. * @param {string} request.filter
  304. * The standard list filter.
  305. * @param {number} request.pageSize
  306. * The standard list page size.
  307. * @param {string} request.pageToken
  308. * The standard list page token.
  309. * @param {object} [options]
  310. * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details.
  311. * @returns {Object}
  312. * An iterable Object that allows [async iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols).
  313. * When you iterate the returned iterable, each element will be an object representing
  314. * [Location]{@link google.cloud.location.Location}. The API will be called under the hood as needed, once per the page,
  315. * so you can stop the iteration when you don't need more results.
  316. * Please see the
  317. * [documentation](https://github.com/googleapis/gax-nodejs/blob/main/client-libraries.md#auto-pagination)
  318. * for more details and examples.
  319. * @example
  320. * const iterable = client.listLocationsAsync(request);
  321. * for await (const response of iterable) {
  322. * // process response
  323. * }
  324. */
  325. listLocationsAsync(request, options) {
  326. request = request || {};
  327. options = options || {};
  328. options.otherArgs = options.otherArgs || {};
  329. options.otherArgs.headers = options.otherArgs.headers || {};
  330. options.otherArgs.headers['x-goog-request-params'] =
  331. routingHeader.fromParams({
  332. name: request.name || '',
  333. });
  334. options = options || {};
  335. const callSettings = new gax.CallSettings(options);
  336. this.initialize();
  337. return this.descriptors.page.listLocations.asyncIterate(this.innerApiCalls['listLocations'], request, callSettings);
  338. }
  339. /**
  340. * Terminate the gRPC channel and close the client.
  341. *
  342. * The client will no longer be usable and all future behavior is undefined.
  343. * @returns {Promise} A promise that resolves when the client is closed.
  344. */
  345. close() {
  346. this.initialize();
  347. if (!this._terminated) {
  348. return this.locationsStub.then(stub => {
  349. this._terminated = true;
  350. stub.close();
  351. });
  352. }
  353. return Promise.resolve();
  354. }
  355. }
  356. exports.LocationsClient = LocationsClient;
  357. //# sourceMappingURL=locationService.js.map