nodejs-google-adwords
Version:
Google Ads API Client Library for Node.js
447 lines (446 loc) • 18.3 kB
JavaScript
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var soap = __importStar(require("soap"));
var lodash_1 = __importDefault(require("lodash"));
var pretty_data_1 = require("pretty-data");
var AdwordsOperationService_1 = require("./AdwordsOperationService");
var XMLService_1 = require("./XMLService");
var SoapService = /** @class */ (function (_super) {
__extends(SoapService, _super);
function SoapService(options) {
var _this = _super.call(this) || this;
_this.verbose = false;
_this.namespace = 'ns1';
_this.authService = options.authService;
_this.url = options.url;
_this.serviceName = options.serviceName;
_this.xmlns = options.xmlns;
_this.header = options.header;
_this.verbose = options.verbose || false;
_this.gzip = options.gzip || true;
return _this;
}
SoapService.prototype.setVerbose = function (val) {
this.verbose = val;
};
/**
* enable/disable http request gzip
*
* @author dulin
* @param {boolean} val
* @memberof SoapService
*/
SoapService.prototype.setGzip = function (gzip) {
this.gzip = gzip;
};
SoapService.prototype.setHeader = function (header) {
this.header = header;
};
SoapService.prototype.getClient = function () {
return __awaiter(this, void 0, void 0, function () {
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (this.client) {
return [2 /*return*/, this.client];
}
_a = this;
return [4 /*yield*/, this.beforeSendRequest()];
case 1:
_a.client = _b.sent();
return [2 /*return*/, this.client];
}
});
});
};
/**
* mutate operation
*
* @author dulin
* @template Operation
* @template Response
* @param {Operation[]} operations
* @returns {Promise<Response>}
* @memberof SoapService
*/
SoapService.prototype.mutateAsync = function (operations, operationType) {
return __awaiter(this, void 0, void 0, function () {
var client, request, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!operations.length) {
throw new Error('operation array is empty');
}
return [4 /*yield*/, this.beforeSendRequest()];
case 1:
client = _a.sent();
request = this.formMutateRequest({ operations: operations, operationType: operationType, mutateMethod: 'mutate' });
return [4 /*yield*/, client.mutateAsync(request)];
case 2:
response = _a.sent();
return [2 /*return*/, this.parseMutateResponse(response)];
}
});
});
};
/**
* parse mutate response
*
* @author dulin
* @template Response
* @param {Response} response
* @returns
* @memberof SoapService
*/
SoapService.prototype.parseMutateResponse = function (response) {
return lodash_1.default.get(response, [0, 'rval'], {});
};
/**
* mutate label
*
* @author dulin
* @template Operation
* @template Rval
* @param {Operation[]} operations
* @returns {Promise<Rval>}
* @memberof SoapService
*/
SoapService.prototype.mutateLabelAsync = function (operations, operationType) {
return __awaiter(this, void 0, void 0, function () {
var client, request, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.beforeSendRequest()];
case 1:
client = _a.sent();
request = this.formMutateRequest({ operations: operations, operationType: operationType, mutateMethod: 'mutateLabel' });
return [4 /*yield*/, client.mutateLabelAsync(request)];
case 2:
response = _a.sent();
return [2 /*return*/, this.parseMutateResponse(response)];
}
});
});
};
/**
* get operation
*
* @author dulin
* @template ServiceSelector
* @template Rval
* @param {ServiceSelector} serviceSelector
* @returns {Promise<Rval>}
* @memberof SoapService
*/
SoapService.prototype.get = function (serviceSelector) {
return __awaiter(this, void 0, void 0, function () {
var credentials, client;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.authService.refreshCredentials()];
case 1:
credentials = _a.sent();
return [4 /*yield*/, this.createSoapClient(this.url, credentials)];
case 2:
client = _a.sent();
return [2 /*return*/, new Promise(function (resolve, reject) {
if (!client) {
return reject(new Error('soap client does not exist'));
}
var request = _this.formGetRequest(serviceSelector);
var requestOptions = _this.formHttpRequestOptions();
client.get(request, function (error, response) {
if (error) {
return reject(error);
}
var rval = _this.parseGetResponse(response);
resolve(rval);
}, requestOptions);
})];
}
});
});
};
/**
* parse get response
*
* @author dulin
* @template Rval
* @param {IResponse<Rval>} response
* @returns {(Rval | undefined)}
* @memberof SoapService
*/
SoapService.prototype.parseGetResponse = function (response) {
return lodash_1.default.get(response, ['rval'], undefined);
};
SoapService.prototype.beforeSendRequest = function () {
return __awaiter(this, void 0, void 0, function () {
var credentials;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.authService.refreshCredentials()];
case 1:
credentials = _a.sent();
return [2 /*return*/, this.createSoapClient(this.url, credentials)];
}
});
});
};
/**
* form get parameter
* https://github.com/mrdulin/nodejs-google-adwords/issues/2
*
* @author dulin
* @private
* @template T
* @param {T} serviceSelector
* @returns
* @memberof SoapService
*/
SoapService.prototype.formGetRequest = function (serviceSelector) {
var getInput = lodash_1.default.get(this.description, [this.serviceName, this.serviceName + "InterfacePort", 'get', 'input'], {});
var parameter = {};
if (getInput.selector) {
parameter = { selector: serviceSelector };
}
else if (getInput.serviceSelector) {
parameter = { serviceSelector: serviceSelector };
}
return parameter;
};
SoapService.prototype.formMutateRequest = function (options) {
var _this = this;
var request = { operations: [] };
var mutateMethod = this.description[this.serviceName][this.serviceName + "InterfacePort"][options.mutateMethod];
var operations = options.operations;
if (lodash_1.default.keys(mutateMethod.input).indexOf('operations[]') > -1) {
lodash_1.default.each(operations, function (operation) {
operation.operand = _this.matchJSONKeyOrder(operation.operand, mutateMethod.input['operations[]'].operand);
request.operations.push(operation);
});
}
if (options.operationType) {
request.operations = lodash_1.default.map(request.operations, function (operation) {
operation.attributes = {
'xsi:type': options.operationType,
};
return operation;
});
}
return request;
};
/**
* XML element order matters
*
* @author dulin
* @private
* @param {*} src
* @param {*} toMatch
* @returns
* @memberof SoapService
*/
SoapService.prototype.matchJSONKeyOrder = function (src, toMatch) {
var orderedObj = {};
var self = this;
lodash_1.default.mapKeys(toMatch, function (v, k) {
// Check and remove [] at the end
if (typeof k !== 'string') {
return;
}
var canBeMore = false;
if (k.substr(-2) === '[]') {
k = k.substr(0, k.length - 2);
canBeMore = true;
}
if (src[k] === undefined) {
return;
}
if (!canBeMore && typeof src[k] === 'object' && typeof v === 'object') {
orderedObj[k] = self.matchJSONKeyOrder(src[k], v);
}
else if (canBeMore && typeof v === 'object' && lodash_1.default.isArray(src[k])) {
orderedObj[k] = [];
lodash_1.default.each(src[k], function (item) {
orderedObj[k].push(self.matchJSONKeyOrder(item, v));
});
}
else {
orderedObj[k] = src[k];
}
});
// Add keys not present in toMatch object, at the end
var currentKeys = lodash_1.default.keys(orderedObj);
lodash_1.default.mapKeys(src, function (v, k) {
if (currentKeys.indexOf(k) === -1) {
orderedObj[k] = src[k];
}
});
return orderedObj;
};
/**
* create soap client
*
* @author dulin
* @private
* @param {string} url
* @param {IOAuthRefreshedCredential} credentials
* @returns {Promise<void>}
* @memberof SoapService
*/
SoapService.prototype.createSoapClient = function (url, credentials) {
return __awaiter(this, void 0, void 0, function () {
var _a, error_1;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (!credentials.access_token) {
throw new Error('access_token required.');
}
_b.label = 1;
case 1:
_b.trys.push([1, 3, , 4]);
_a = this;
return [4 /*yield*/, soap.createClientAsync(url, {})];
case 2:
_a.client = _b.sent();
this.client.addSoapHeader({ RequestHeader: this.header }, this.serviceName, this.namespace, this.xmlns);
this.client.setSecurity(new soap.BearerSecurity(credentials.access_token));
this.description = this.client.describe();
return [2 /*return*/, this.listenSoapClientEvents(this.client)];
case 3:
error_1 = _b.sent();
console.error(error_1);
throw new Error('create soap client failed.');
case 4: return [2 /*return*/];
}
});
});
};
/**
* form http request core options
*
* gzip compress
* https://developers.google.com/adwords/api/docs/guides/bestpractices#use_compression
* For backwards-compatibility, response compression is not supported by default. To accept gzip-compressed responses, set the gzip option to true
*
* @author dulin
* @private
* @returns {CoreOptions}
* @memberof SoapService
*/
SoapService.prototype.formHttpRequestOptions = function () {
var options = {
headers: {
Connection: 'keep-alive',
},
gzip: this.gzip,
};
if (this.gzip && options.headers) {
options.headers['User-Agent'] = this.header.userAgent + " (gzip)";
options.headers['Accept-Encoding'] = 'gzip';
}
return options;
};
/**
* handle soap client events
* https://developers.google.com/adwords/api/docs/guides/call-structure#response_headers
*
* @author dulin
* @private
* @memberof SoapService
*/
SoapService.prototype.listenSoapClientEvents = function (client) {
var _this = this;
if (!client) {
throw new Error('soap client is required');
}
client.on('request', function (xml, eid) {
if (_this.verbose) {
console.log('Soap request (Envelope) including headers: ', pretty_data_1.pd.xml(xml));
console.log('Soap request exchange id: ', eid);
}
});
client.on('soapError', function (error, eid) {
if (_this.verbose) {
console.error(error);
}
});
client.on('response', function (body, response, eid) {
if (_this.verbose) {
console.log('Soap response body: ', pretty_data_1.pd.xml(body));
console.log('Soap response: ', pretty_data_1.pd.json(response));
}
var operations = XMLService_1.XMLService.extractValueFromElement(body, 'operations');
var responseTime = XMLService_1.XMLService.extractValueFromElement(body, 'responseTime');
var message = "Soap requestId: " + eid;
message += operations ? ", operations: " + operations : '';
message += responseTime ? ", responseTime: " + responseTime + "ms" : '';
console.log(message);
});
return client;
};
return SoapService;
}(AdwordsOperationService_1.AdwordsOperartionService));
exports.SoapService = SoapService;