@google-cloud/nodejs-common 1.0.4 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -11,68 +11,65 @@ and [Data Tasks Coordinator]. This library includes:
11
11
  1. Wrapper for some Google APIs for integration, mainly
12
12
  for [GMP and Google Ads Connector]:
13
13
 
14
- * Google Analytics data import
15
- * Google Analytics measurement protocol
16
- * Campaign Manager offline conversion upload
17
- * Search Ads 360 conversions upload
18
- * Google Ads click conversions upload
19
- * Google Ads customer match upload
20
- * Google Ads conversions scheduled uploads based on Google Sheets
21
- * Measurement Protocol Google Analytics 4
14
+ - Google Analytics data import
15
+ - Google Analytics measurement protocol
16
+ - Campaign Manager offline conversion upload
17
+ - Search Ads 360 conversions upload
18
+ - Google Ads click conversions upload
19
+ - Google Ads customer match upload
20
+ - Google Ads enhanced conversions upload
21
+ - Google Ads conversions scheduled uploads based on Google Sheets
22
+ - Measurement Protocol Google Analytics 4
22
23
 
23
24
  1. Wrapper for some Google APIs for reporting, mainly
24
25
  for [Data Tasks Coordinator]:
25
26
 
26
- * Google Ads reporting
27
- * Campaign Manager reporting
28
- * Search Ads 360 reporting
29
- * Display and Video 360 reporting
30
- * YouTube Data API
31
- * Ads Data Hub querying
27
+ - Google Ads reporting
28
+ - Campaign Manager reporting
29
+ - Search Ads 360 reporting
30
+ - Display and Video 360 reporting
31
+ - YouTube Data API
32
+ - Ads Data Hub querying
32
33
 
33
34
  1. Utilities wrapper class for Google Cloud Products:
34
35
 
35
- * **Firestore Access Object**: Firestore has two modes which are excluded to
36
- each other and can't be changed once selected in a Cloud Project[[2]].
37
- This class, with its two successors offer a unified interface to operate
38
- data objects on either Firestore or Datastore.
36
+ - **Firestore Access Object**: Firestore has two modes which are excluded to
37
+ each other and can't be changed once selected in a Cloud Project[[2]].
38
+ This class, with its two successors offer a unified interface to operate
39
+ data objects on either Firestore or Datastore.
39
40
 
40
- * **AutoMl Tables API**: Offers a unified entry to use this API based on
41
- Google Cloud client library combined with REST requests to service
42
- directly due to some functionalities missed in the client library.
41
+ - **AutoMl Tables API**: Offers a unified entry to use this API based on
42
+ Google Cloud client library combined with REST requests to service
43
+ directly due to some functionalities missed in the client library.
43
44
 
44
- * **Vertex AI API**: Offers a unified entry to use this API based on Google
45
- Cloud client library.
45
+ - **Vertex AI API**: Offers a unified entry to use this API based on Google
46
+ Cloud client library.
46
47
 
47
- * **Pub/Sub Utilities**: Offers utilities functions to create topics and
48
- subscriptions for Pub/Sub, as well as the convenient way to publish a
49
- message.
48
+ - **Pub/Sub Utilities**: Offers utilities functions to create topics and
49
+ subscriptions for Pub/Sub, as well as the convenient way to publish a
50
+ message.
50
51
 
51
- * **Storage Utilities**: Offers functions to manipulate the files on Cloud
52
- Storage. The main functions are:
52
+ - **Storage Utilities**: Offers functions to manipulate the files on Cloud
53
+ Storage. The main functions are:
53
54
 
54
- * Reading a given length (or slightly less) content without breaking a
55
- line;
56
- * Splitting a file into multiple files with the given length (or
57
- slightly less) without breaking a line;
58
- * Merging files into one file.
55
+ - Reading a given length (or slightly less) content without breaking a
56
+ line;
57
+ - Splitting a file into multiple files with the given length (or
58
+ slightly less) without breaking a line;
59
+ - Merging files into one file.
59
60
 
60
- * **Cloud Scheduler Adapter**: A wrapper to pause and resume Cloud Scheduler
61
- jobs.
61
+ - **Cloud Scheduler Adapter**: A wrapper to pause and resume Cloud Scheduler
62
+ jobs.
62
63
 
63
- * **Cloud Functions Adapter**: Cloud Functions have different parameters in
64
- different environments, e.g. Node6 vs Node8[[1]]. This utility file offers
65
- an adapter to wrap a Node8 Cloud Functions into Node6 and Node8 compatible
66
- functions.
64
+ - **Cloud Functions Adapter**: Cloud Functions have different parameters in
65
+ different environments, e.g. Node6 vs Node8[[1]]. This utility file offers
66
+ an adapter to wrap a Node8 Cloud Functions into Node6 and Node8 compatible
67
+ functions.
67
68
 
68
69
  1. A share library for [Bash] to facilitate installation tasks.
69
70
 
70
- [GMP and Google Ads Connector]:https://github.com/GoogleCloudPlatform/cloud-for-marketing/tree/master/marketing-analytics/activation/gmp-googleads-connector
71
-
72
- [Data Tasks Coordinator]:https://github.com/GoogleCloudPlatform/cloud-for-marketing/tree/master/marketing-analytics/activation/data-tasks-coordinator
73
-
74
- [1]:https://cloud.google.com/functions/docs/writing/background#functions-writing-background-hello-pubsub-node8-10
75
-
76
- [2]:https://cloud.google.com/datastore/docs/concepts/overview#comparison_with_traditional_databases
77
-
78
- [Bash]:https://www.gnu.org/software/bash/
71
+ [gmp and google ads connector]: https://github.com/GoogleCloudPlatform/cloud-for-marketing/tree/master/marketing-analytics/activation/gmp-googleads-connector
72
+ [data tasks coordinator]: https://github.com/GoogleCloudPlatform/cloud-for-marketing/tree/master/marketing-analytics/activation/data-tasks-coordinator
73
+ [1]: https://cloud.google.com/functions/docs/writing/background#functions-writing-background-hello-pubsub-node8-10
74
+ [2]: https://cloud.google.com/datastore/docs/concepts/overview#comparison_with_traditional_databases
75
+ [bash]: https://www.gnu.org/software/bash/
@@ -173,7 +173,7 @@ project ID: [${current_project}]"
173
173
  project=${project:-"${current_project}"}
174
174
  target_project=${project}
175
175
  fi
176
- if [[ -n ${current_project} && \
176
+ if [[ -z ${current_project} || \
177
177
  ${current_project} != "${target_project}" ]];then
178
178
  printf '%s' "Setting the Google Cloud project to [${target_project}]..."
179
179
  gcloud config set project "${target_project}"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@google-cloud/nodejs-common",
3
- "version": "1.0.4",
3
+ "version": "1.0.5",
4
4
  "description": "A NodeJs common library for solutions based on Cloud Functions",
5
5
  "author": "Google Inc.",
6
6
  "license": "Apache-2.0",
@@ -37,9 +37,11 @@ class AdsDataHub {
37
37
  *
38
38
  * @param {GaxiosOptions|undefined=} options Used to setup for tests.
39
39
  * @param {string|undefined=} customerId ADH customer id.
40
+ * @param {!Object<string,string>=} env The environment object to hold env
41
+ * variables.
40
42
  */
41
- constructor(options, customerId = undefined) {
42
- const authClient = new AuthClient(API_SCOPES);
43
+ constructor(options, customerId = undefined, env = process.env) {
44
+ const authClient = new AuthClient(API_SCOPES, env);
43
45
  this.auth = authClient.getDefaultAuth();
44
46
  /** @const{GaxiosOptions} */ this.options = options || {};
45
47
  /** @const{string|undefined=} */ this.customerId = customerId;
@@ -32,11 +32,11 @@ const API_VERSION = 'v1';
32
32
  * Google cloud client libraries.
33
33
  */
34
34
  class CloudPlatformApis {
35
- constructor(projectId = process.env['GCP_PROJECT']) {
35
+ constructor(env = process.env) {
36
36
  /** @const {!AuthClient} */
37
- const authClient = new AuthClient(API_SCOPES);
38
- this.auth = authClient.getApplicationDefaultCredentials();
39
- this.projectId = projectId;
37
+ const authClient = new AuthClient(API_SCOPES, env);
38
+ this.auth = authClient.getDefaultAuth();
39
+ this.projectId = env['GCP_PROJECT'];
40
40
  }
41
41
 
42
42
  /**
@@ -56,8 +56,13 @@ let RequestBody;
56
56
  * https://developers.google.com/bid-manager/how-tos/authorizing
57
57
  */
58
58
  class DoubleClickBidManager {
59
- constructor() {
60
- const authClient = new AuthClient(API_SCOPES);
59
+ /**
60
+ * @constructor
61
+ * @param {!Object<string,string>=} env The environment object to hold env
62
+ * variables.
63
+ */
64
+ constructor(env = process.env) {
65
+ const authClient = new AuthClient(API_SCOPES, env);
61
66
  const auth = authClient.getDefaultAuth();
62
67
  /** @const {!google.doubleclickbidmanager} */
63
68
  this.instance = google.doubleclickbidmanager({
@@ -104,6 +109,20 @@ class DoubleClickBidManager {
104
109
  return response.data.queryId;
105
110
  }
106
111
 
112
+ /**
113
+ * Deletes a query.
114
+ * @param {number} queryId
115
+ * @return {!Promise<boolean>} Whether the query was deleted.
116
+ */
117
+ async deleteQuery(queryId) {
118
+ try {
119
+ await this.instance.queries.deletequery({ queryId });
120
+ return true;
121
+ } catch (error) {
122
+ console.error(error);
123
+ return false;
124
+ }
125
+ }
107
126
  }
108
127
 
109
128
  module.exports = {
@@ -31,6 +31,8 @@ const {
31
31
  services: {
32
32
  UploadClickConversionsRequest,
33
33
  UploadClickConversionsResponse,
34
+ UploadConversionAdjustmentsRequest,
35
+ UploadConversionAdjustmentsResponse,
34
36
  UploadUserDataRequest,
35
37
  UploadUserDataResponse,
36
38
  UserDataOperation,
@@ -51,8 +53,9 @@ const API_SCOPES = Object.freeze(['https://www.googleapis.com/auth/adwords',]);
51
53
 
52
54
  /**
53
55
  * List of properties that will be taken from the data file as elements of a
54
- * conversion.
56
+ * conversion or a conversion adjustment.
55
57
  * @see https://developers.google.com/google-ads/api/reference/rpc/latest/ClickConversion
58
+ * @see https://developers.google.com/google-ads/api/reference/rpc/latest/ConversionAdjustment
56
59
  * @type {Array<string>}
57
60
  */
58
61
  const PICKED_PROPERTIES = [
@@ -65,6 +68,10 @@ const PICKED_PROPERTIES = [
65
68
  'conversion_value',
66
69
  'currency_code',
67
70
  'order_id',
71
+ 'adjustment_type',
72
+ 'adjustment_date_time',
73
+ 'user_agent',
74
+ 'gclid_date_time_pair',
68
75
  ];
69
76
 
70
77
  /**
@@ -88,9 +95,11 @@ const IDENTIFIERS = [
88
95
  const MAX_IDENTIFIERS_PER_USER = 20;
89
96
 
90
97
  /**
91
- * Configuration for uploading click conversions for Google Ads, includes:
98
+ * Configuration for uploading click conversions or conversion adjustments for
99
+ * Google Ads, includes:
92
100
  * gclid, conversion_action, conversion_date_time, conversion_value,
93
- * currency_code, order_id, external_attribution_data, etc.
101
+ * currency_code, order_id, external_attribution_data,
102
+ * adjustment_type, adjustment_date_time, user_agent, gclid_date_time_pair, etc.
94
103
  * @see PICKED_PROPERTIES
95
104
  *
96
105
  * Other properties that will be used to build the conversions but not picked by
@@ -116,12 +125,15 @@ const MAX_IDENTIFIERS_PER_USER = 20;
116
125
  * conversion_value: number,
117
126
  * currency_code:(string|undefined),
118
127
  * order_id: (string|undefined),
119
- * user_identifier_source:(UserIdentifierSource|undefined),
128
+ * adjustment_type: (string|undefined),
129
+ * adjustment_date_time: (!ConversionAdjustmentType|undefined),
130
+ * user_agent: (string|undefined),
131
+ * user_identifier_source:(!UserIdentifierSource|undefined),
120
132
  * custom_variable_tags:(!Array<string>|undefined),
121
133
  * customVariables:(!Object<string,string>|undefined),
122
134
  * }}
123
135
  */
124
- let ClickConversionConfig;
136
+ let ConversionConfig;
125
137
 
126
138
  /**
127
139
  * Configuration for uploading customer match to Google Ads, includes:
@@ -255,7 +267,7 @@ class GoogleAds {
255
267
  * of click conversions.
256
268
  * @param {string} customerId
257
269
  * @param {string} loginCustomerId Login customer account ID (Mcc Account id).
258
- * @param {!ClickConversionConfig} adsConfig Default click conversion params
270
+ * @param {!ConversionConfig} adsConfig Default click conversion params
259
271
  * @return {!SendSingleBatch} Function which can send a batch of hits to
260
272
  * Google Ads API.
261
273
  */
@@ -268,7 +280,7 @@ class GoogleAds {
268
280
  * @return {!BatchResult}
269
281
  */
270
282
  return async (lines, batchId) => {
271
- /** @type {!Array<ClickConversionConfig>} */
283
+ /** @type {!Array<ConversionConfig>} */
272
284
  const conversions = lines.map(
273
285
  (line) => buildClickConversionFromLine(line, adsConfig, customerId));
274
286
  /** @const {BatchResult} */
@@ -300,6 +312,57 @@ class GoogleAds {
300
312
  }
301
313
  }
302
314
 
315
+ /**
316
+ * Returns the function to send out a request to Google Ads API with a batch
317
+ * of conversion adjustments.
318
+ * @param {string} customerId
319
+ * @param {string} loginCustomerId Login customer account ID (Mcc Account id).
320
+ * @param {!ConversionConfig} adsConfig Default conversion adjustments
321
+ * params.
322
+ * @return {!SendSingleBatch} Function which can send a batch of hits to
323
+ * Google Ads API.
324
+ */
325
+ getUploadConversionAdjustmentFn(customerId, loginCustomerId, adsConfig) {
326
+ /**
327
+ * Sends a batch of hits to Google Ads API.
328
+ * @param {!Array<string>} lines Data for single request. It should be
329
+ * guaranteed that it doesn't exceed quota limitation.
330
+ * @param {string} batchId The tag for log.
331
+ * @return {!BatchResult}
332
+ */
333
+ return async (lines, batchId) => {
334
+ /** @type {!Array<ConversionConfig>} */
335
+ const conversions = lines.map(
336
+ (line) => buildClickConversionFromLine(line, adsConfig, customerId));
337
+ /** @const {BatchResult} */
338
+ const batchResult = {
339
+ result: true,
340
+ numberOfLines: lines.length,
341
+ };
342
+ try {
343
+ const response = await this.uploadConversionAdjustments(conversions,
344
+ customerId, loginCustomerId);
345
+ const {results, partial_failure_error: failed} = response;
346
+ if (this.logger.isDebugEnabled()) {
347
+ const orderId = results.map((conversion) => conversion.order_id);
348
+ this.logger.debug('Uploaded order_id:', orderId);
349
+ }
350
+ if (failed) {
351
+ this.logger.info('partial_failure_error:', failed.message);
352
+ const failures = failed.details.map(
353
+ ({value}) => GoogleAdsFailure.decode(value));
354
+ this.extraFailedLines_(batchResult, failures, lines, 0);
355
+ }
356
+ return batchResult;
357
+ } catch (error) {
358
+ this.logger.error(
359
+ `Error in upload conversion adjustments batch: ${batchId}`, error);
360
+ this.updateBatchResultWithError_(batchResult, error, lines, 0);
361
+ return batchResult;
362
+ }
363
+ }
364
+ }
365
+
303
366
  /**
304
367
  * Updates the BatchResult based on errors.
305
368
  *
@@ -434,7 +497,7 @@ class GoogleAds {
434
497
  * Uploads click conversions to google ads account.
435
498
  * It requires an array of click conversions and customer id.
436
499
  * In DEBUG mode, this function will only validate the conversions.
437
- * @param {Array<ClickConversionConfig>} clickConversions ClickConversions
500
+ * @param {Array<ConversionConfig>} clickConversions ClickConversions
438
501
  * @param {string} customerId
439
502
  * @param {string} loginCustomerId Login customer account ID (Mcc Account id).
440
503
  * @return {!Promise<!UploadClickConversionsResponse>}
@@ -451,6 +514,31 @@ class GoogleAds {
451
514
  return customer.conversionUploads.uploadClickConversions(request);
452
515
  }
453
516
 
517
+ /**
518
+ * Uploads conversion adjustments to google ads account.
519
+ * It requires an array of conversion adjustments and customer id.
520
+ * In DEBUG mode, this function will only validate the conversion adjustments.
521
+ * @param {Array<ConversionAdjustment>} conversionAdjustments Conversion
522
+ * adjustments.
523
+ * @param {string} customerId
524
+ * @param {string} loginCustomerId Login customer account ID (Mcc Account id).
525
+ * @return {!Promise<!UploadConversionAdjustmentsResponse>}
526
+ */
527
+ uploadConversionAdjustments(conversionAdjustments, customerId,
528
+ loginCustomerId) {
529
+ this.logger.debug('Upload conversion adjustments for customerId:',
530
+ customerId);
531
+ const customer = this.getGoogleAdsApiCustomer_(loginCustomerId, customerId);
532
+ const request = new UploadConversionAdjustmentsRequest({
533
+ conversion_adjustments: conversionAdjustments,
534
+ customer_id: customerId,
535
+ validate_only: this.debugMode, // when true makes no changes
536
+ partial_failure: true, // Will still create the non-failed entities
537
+ });
538
+ return customer.conversionAdjustmentUploads.uploadConversionAdjustments(
539
+ request);
540
+ }
541
+
454
542
  /**
455
543
  * Returns the id of Conversion Custom Variable with the given tag.
456
544
  * @param {string} tag Custom Variable tag.
@@ -622,7 +710,7 @@ class GoogleAds {
622
710
  /**
623
711
  * Returns a conversion object based the given config and line data.
624
712
  * @param {string} line A JSON string of a conversion data.
625
- * @param {ClickConversionConfig} config Default click conversion params
713
+ * @param {ConversionConfig} config Default click conversion params
626
714
  * @param {string} customerId
627
715
  * @return {object} A conversion
628
716
  */
@@ -657,7 +745,7 @@ const buildClickConversionFromLine = (line, config, customerId) => {
657
745
  }
658
746
 
659
747
  module.exports = {
660
- ClickConversionConfig,
748
+ ConversionConfig,
661
749
  CustomerMatchRecord,
662
750
  CustomerMatchConfig,
663
751
  GoogleAds,
package/src/apis/index.js CHANGED
@@ -88,7 +88,7 @@ exports.bigquery = require('./bigquery.js');
88
88
  * APIs integration class for Google Ads.
89
89
  * @const {{
90
90
  * GoogleAds:!GoogleAds,
91
- * ClickConversionConfig:!ClickConversionConfig,
91
+ * ConversionConfig:!ConversionConfig,
92
92
  * CustomerMatchConfig: !CustomerMatchConfig,
93
93
  * CustomerMatchRecord: !CustomerMatchRecord,
94
94
  * ReportQueryConfig:!ReportQueryConfig,
@@ -20,8 +20,7 @@
20
20
 
21
21
  const winston = require('winston');
22
22
  const {inspect} = require('util');
23
- const {LoggingWinston} = require('@google-cloud/logging-winston');
24
- const {CloudPlatformApis} = require('../apis/cloud_platform_apis.js');
23
+ const { LoggingWinston } = require('@google-cloud/logging-winston');
25
24
 
26
25
  /**
27
26
  * The result of a batch of data sent to target API. The batch here means the
@@ -498,37 +497,6 @@ const extractObject = (paths) => {
498
497
  };
499
498
  };
500
499
 
501
- /**
502
- * Checks whether the permissions are granted for current authentication.
503
- * This function will be invoked during the deployment of a specific solution,
504
- * e.g. Tentacles, to make sure the operator has the proper permissions to
505
- * carry on. If the operator doesn't have enough permissions, it will exit with
506
- * status code 1 to let the invoker (the Bash installation script) know that it
507
- * doesn't pass.
508
- * @param {!Array<string>} permissions Array of permissions to check.
509
- * @param {string} projectId The Id of Cloud project.
510
- * @return {!Promise<undefined>}
511
- */
512
- const checkPermissions = (permissions,
513
- projectId = process.env['GCP_PROJECT']) => {
514
- const cloudPlatformApis = new CloudPlatformApis(projectId);
515
- return cloudPlatformApis.testIamPermissions(permissions)
516
- .then((grantedPermissions) => {
517
- console.log(grantedPermissions);
518
- grantedPermissions = grantedPermissions || [];
519
- if (grantedPermissions.length < permissions.length) {
520
- const missedPermissions = permissions.filter(
521
- (permission) => grantedPermissions.indexOf(permission) === -1);
522
- console.error(`[MISSED] ${missedPermissions.join(',')}.`);
523
- process.exit(1);
524
- }
525
- })
526
- .catch((error) => {
527
- console.error(`[ERROR] ${error.message}`);
528
- process.exit(1);
529
- });
530
- };
531
-
532
500
  /**
533
501
  * For more details, see:
534
502
  * https://developers.google.com/google-ads/api/docs/rest/design/json-mappings
@@ -565,7 +533,6 @@ module.exports = {
565
533
  replaceParameters,
566
534
  getFilterFunction,
567
535
  extractObject,
568
- checkPermissions,
569
536
  changeNamingFromSnakeToUpperCamel,
570
537
  changeNamingFromSnakeToLowerCamel,
571
538
  };