"use strict";
/**
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var axios_1 = __importDefault(require("axios"));
var options_1 = require("./options");
// tslint:disable-next-line no-var-requires
var pkg = require('../../package.json');
var PRODUCT_NAME = 'google-api-nodejs-client';
/**
 * Axios will use XHR if it is available. In the case of Electron,
 * since XHR is there it will try to use that. This leads to OPTIONS
 * preflight requests which googleapis DOES NOT like. This line of
 * code pins the adapter to ensure it uses node.
 * https://github.com/google/google-api-nodejs-client/issues/1083
 */
axios_1.default.defaults.adapter = require('axios/lib/adapters/http');
var DefaultTransporter = /** @class */ (function () {
    function DefaultTransporter() {
    }
    /**
     * Configures request options before making a request.
     * @param opts AxiosRequestConfig options.
     * @return Configured options.
     */
    DefaultTransporter.prototype.configure = function (opts) {
        if (opts === void 0) { opts = {}; }
        // set transporter user agent
        opts.headers = opts.headers || {};
        var uaValue = opts.headers['User-Agent'];
        if (!uaValue) {
            opts.headers['User-Agent'] = DefaultTransporter.USER_AGENT;
        }
        else if (!uaValue.includes(PRODUCT_NAME + "/")) {
            opts.headers['User-Agent'] =
                uaValue + " " + DefaultTransporter.USER_AGENT;
        }
        return opts;
    };
    DefaultTransporter.prototype.request = function (opts, callback) {
        var _this = this;
        // ensure the user isn't passing in request-style options
        opts = this.configure(opts);
        try {
            options_1.validate(opts);
        }
        catch (e) {
            if (callback) {
                return callback(e);
            }
            else {
                throw e;
            }
        }
        if (callback) {
            axios_1.default(opts)
                .then(function (r) {
                callback(null, r);
            })
                .catch(function (e) {
                callback(_this.processError(e));
            });
        }
        else {
            return axios_1.default(opts).catch(function (e) {
                throw _this.processError(e);
            });
        }
    };
    /**
     * Changes the error to include details from the body.
     */
    DefaultTransporter.prototype.processError = function (e) {
        var res = e.response;
        var err = e;
        var body = res ? res.data : null;
        if (res && body && body.error && res.status !== 200) {
            if (typeof body.error === 'string') {
                err.message = body.error;
                err.code = res.status.toString();
            }
            else if (Array.isArray(body.error.errors)) {
                err.message =
                    body.error.errors.map(function (err2) { return err2.message; }).join('\n');
                err.code = body.error.code;
                err.errors = body.error.errors;
            }
            else {
                err.message = body.error.message;
                err.code = body.error.code || res.status;
            }
        }
        else if (res && res.status >= 400) {
            // Consider all 4xx and 5xx responses errors.
            err.message = body;
            err.code = res.status.toString();
        }
        return err;
    };
    /**
     * Default user agent.
     */
    DefaultTransporter.USER_AGENT = PRODUCT_NAME + "/" + pkg.version;
    return DefaultTransporter;
}());
exports.DefaultTransporter = DefaultTransporter;
//# sourceMappingURL=transporters.js.map