"use strict";
var ApiClientBase_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ApiClientBase = exports.TypeName = void 0;
const tslib_1 = require("tslib");
const https = require("https");
const querystring = require("querystring");
const axios_1 = require("axios");
const inversify_1 = require("inversify");
// import _ from "lodash";
const urlPattern = require("url-pattern");
const codiac_common_1 = require("@codiac.io/codiac-common");
const contracts = require("@codiac.io/codiac-common/contracts");
const contracts_1 = require("@codiac.io/codiac-common/contracts");
class TypeName {
    static endpointSpec(entityType) {
        if (typeof entityType == "string") {
            return `endpointSpec<${entityType}>`;
        }
        else {
            return `endpointSpec<${(0, codiac_common_1.typeNameOf)(entityType)}>`;
        }
    }
    // TODO: Promote this to a common/shared library
    static arrayOf(entityType) {
        if (typeof entityType == "string") {
            return `Array<${entityType}>`;
        }
        else {
            return `Array<${(0, codiac_common_1.typeNameOf)(entityType)}>`;
        }
    }
    static criteriaFor(entityType) {
        if (typeof entityType == "string") {
            return `ICriteria<${entityType}>`;
        }
        else {
            return `ICriteria<${(0, codiac_common_1.typeNameOf)(entityType)}>`;
        }
    }
}
exports.TypeName = TypeName;
let ApiClientBase = ApiClientBase_1 = class ApiClientBase /* extends AuthClientBase */ {
    static bootstrap_base(endpointsJson, logger) {
        // MarkStartHere("This may be the only part of this class that makes this client unique. \
        // Perhaps this should be loaded form a json file?  Can we pass types in that way?");
        // // We can do it like this
        // this.endpointSpecs.bind<endpointSpec<Asset>>(TypeName.endpointSpec(Asset)).toConstantValue(
        //   new endpointSpec<Asset>(Asset, httpRestVerb.POST, "/assets/new")
        // );
        // // or we can do it like this
        // let createMany = { 
        // entityType: Array,
        // httpMethod: httpRestVerb.POST,
        // route: "/assets"
        // };
        // // TODO: this isnt binding by httpRestVerb - it needs to be - perhaps use named bindings?
        // let typeName = TypeName.endpointSpec(TypeName.arrayOf(Asset));
        // this.endpointSpecs.bind<endpointSpec<Array<Asset>>>(typeName).toConstantValue(createMany);
        // // can we do it like this?  (this would let us keep it all in a generated or even retrieved json file)
        // let updateJson = '{ "entityType": "Asset", "httpMethod": "POST", "route": "/assets" }';
        // let update = JSON.parse(updateJson);
        // this.endpointSpecs.bind(TypeName.endpointSpec(update.entityType)).toConstantValue(update);
        this.registerSerializerFor(contracts.StringFilter, new contracts_1.StringFilterExpressionSerializer(true));
        // this.registerSerializerFor<contracts.StringListFilter>(contracts.StringListFilter, contracts.StringListFilter.toExpression);
        // this.registerSerializerFor<contracts.NumericFilter>(contracts.NumericFilter, contracts.NumericFilter.toExpression);
        // this.registerSerializerFor<contracts.NumericListFilter>(contracts.NumericListFilter, contracts.NumericListFilter.toExpression);
        for (let index in endpointsJson) {
            let spec = endpointsJson[index]; // This is dodging type safety and assumes data integrity in the json file.  We should cast
            let nameKey = spec.httpMethod.toLowerCase();
            if (logger)
                logger.trace(`Adding endpoint spec to client endpoint registry: ${spec.entityType}, '${nameKey} ${spec.route}'`);
            this.endpointSpecs
                .bind(TypeName.endpointSpec(spec.entityType)) // Consider .properBind()
                .toConstantValue(spec)
                .whenTargetNamed(nameKey);
        }
    }
    /** For special serializers (eg: StringFilter, etc).
     * Maps the given serializer for use on the given type
     * when later converting input to an http request.
     * NOTE:  a default serializer will be used if reqd and none has been registered here.
     */
    static registerSerializerFor(valueType, serializer) {
        let typeKey = "";
        if (typeof valueType == "string") {
            typeKey = valueType;
        }
        else {
            typeKey = (0, codiac_common_1.typeNameOf)(valueType);
        }
        // All this bc inversify's bind command wont overwrite and results in ambiguous bindings 
        if (this.serializers.isBoundNamed(codiac_common_1.INTERFACES.ISerializer, typeKey)) {
            // I think this DROPS ALL the other named bindings for this service identifier...
            this.serializers.rebind(codiac_common_1.INTERFACES.ISerializer)
                .toConstantValue(serializer)
                .whenTargetNamed(typeKey);
        }
        else {
            this.serializers.bind(codiac_common_1.INTERFACES.ISerializer)
                .toConstantValue(serializer)
                .whenTargetNamed(typeKey);
        }
    }
    /** Returns undefined when no serializer has been registered for the given valueType. */
    static getSerializerFor(valueType) {
        let typeKey = "";
        if (typeof valueType == "string") {
            typeKey = valueType;
        }
        else {
            typeKey = (0, codiac_common_1.typeNameOf)(valueType);
        }
        let ser;
        if (this.serializers.isBoundNamed(codiac_common_1.INTERFACES.ISerializer, typeKey)) {
            ser = this.serializers.getNamed(codiac_common_1.INTERFACES.ISerializer, typeKey);
        }
        return ser;
    }
    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *   _____          _                         ___  ___               _
     *  |_   _|        | |                        |  \/  |              | |
     *    | | _ __  ___| |_ __ _ _ __   ___ ___   | .  . | ___ _ __ ___ | |__   ___ _ __ ___
     *    | || '_ \/ __| __/ _` | '_ \ / __/ _ \  | |\/| |/ _ \ '_ ` _ \| '_ \ / _ \ '__/ __|
     *   _| || | | \__ \ || (_| | | | | (_|  __/  | |  | |  __/ | | | | | |_) |  __/ |  \__ \
     *   \___/_| |_|___/\__\__,_|_| |_|\___\___|  \_|  |_/\___|_| |_| |_|_.__/ \___|_|  |___/
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
    /** Local interface for a remote Api.
     * @param apiRootUrl Override for this.GetDefaultRootUrl().  Fully qualified base url of the api.  That is, prepending it to any individual endpoint route will yield the fully qualified url for that endpoint.
     * @param authToken User token for the api this client is targeting.
     *                  NOTE: Also must get hydrated if child class runs successful attempts of authenticate / refreshToken / switchTenant / registerTenant.
    */
    constructor(logger, apiRootUrl, authToken) {
        this.authToken = authToken;
        this.apiRootUrl = apiRootUrl || this.GetDefaultRootUrl();
        this.tokenHeaderName = ApiClientBase_1.DEFAULT_TOKEN_HEADER_PARAM;
        this.logger = logger;
    }
    /** Sets the user context to impersonate in requests made to the api. */
    setUserToken(token) {
        this.authToken = token;
    }
    // =============================
    // METHODS CALLING API ENDPOINTS
    // =============================
    /** Retrieves the registered endpoint spec for the given request type and httpMethod.
     *  Throws exception if the given entity type and http method are not found.
     */
    getEndpointFor(entityType, httpMethod) {
        let spec;
        let reqType = TypeName.endpointSpec(entityType);
        let specs = [];
        if (ApiClientBase_1.endpointSpecs.isBoundNamed(reqType, httpMethod.toLowerCase())) {
            specs = ApiClientBase_1.endpointSpecs.getAllNamed(reqType, httpMethod.toLowerCase());
        }
        if (specs.length > 0) {
            spec = specs[0]; // we're just gonna take the first one.
        }
        else {
            throw new Error(`Client error: No endpoint registered for [${httpMethod} ${reqType}]`);
        }
        return spec;
    }
    /**  Produces the value for the "Authorization" http header in an RFC 2617 Basic Authentication scheme.
     * Consists of the string "Basic " followed by a colon-separated, base64 encoded string of the username and password.
     * eg:  for userid "Aladdin" and password "open sesame", this function will return "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==".
     * @see https://tools.ietf.org/html/rfc2617#page-4 RFC 2617 HTTP Authentication - Assembling the header value for a basic authentication request. */
    static buildBasicAuthenticationHeader(userName, passwordOrApiKey) {
        let creds = [userName, passwordOrApiKey].join(":");
        let credsEncoded = Buffer.from(creds).toString('base64');
        let headerValue = `Basic ${credsEncoded}`;
        return headerValue;
    }
    /** Fires off an http request to the remote api.
     * Throws any encountered exceptions
     * (api exceptions dont get raised: they get passed back in the response envelope).
     *
     * @param httpVerb
     * @param url Can be relative to this.apiBaseUrl or fully qualified.
     * @param req
     * @param headers
     */
    makeHttpCall(httpVerb, url, req, headers) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                try {
                    this.logger.detail(`Api client making request: ${httpVerb}  ${url === null || url === void 0 ? void 0 : url.split("?")[0]}`);
                    let agent = new https.Agent({ rejectUnauthorized: false });
                    let reqHeaders = {};
                    reqHeaders["content-type"] = "application/json";
                    if (this.authToken) {
                        reqHeaders[this.tokenHeaderName] = this.authToken;
                    }
                    if (headers) {
                        for (let headerKey in headers) {
                            if (headers[headerKey])
                                reqHeaders[headerKey] = headers[headerKey];
                        }
                    }
                    let axiosOptions = {
                        "headers": reqHeaders,
                        "httpsAgent": agent
                    };
                    if (url.indexOf("://") < 0) {
                        axiosOptions.baseURL = this.apiRootUrl;
                    }
                    // TODO:  Consider a different http base library for this:
                    // https://www.npmjs.com/package/got
                    // https://www.npmjs.com/package/node-fetch
                    // let apiResponse = await axios.request<TResponse>({ ...axiosOptions, url: url, method: httpVerb, data: req });
                    return axios_1.default.request(Object.assign(Object.assign({}, axiosOptions), { url: url, method: httpVerb, data: req }))
                        .then(res => {
                        this.logger.debug(`Raw response from [${httpVerb} ${url === null || url === void 0 ? void 0 : url.split("?")[0]}] against apiRootUrl: [${this.apiRootUrl}] [status: ${res.status}  ${res.statusText}]`);
                        if (res.headers && res.headers.authorization)
                            this.authToken = res.headers.authorization;
                        resolve([res.data, res.headers]);
                    })
                        .catch(err => {
                        // this.logger.debug(`Error making request [${httpVerb} ${url}] against apiRootUrl: [${this.apiRootUrl}]: ${err.message || ""}]`);
                        // reject(err);
                        // Might need to do this if axios throws on non-200s...
                        if (err.response) {
                            let axr = err.response;
                            let errMessage = `Remote API returned failure http status: ${axr.status || ""} ${axr.statusText || ""}.`;
                            this.logger.debug(errMessage);
                            const defaultErrResponse = new contracts.Result(false, errMessage, new Error(errMessage));
                            // Trying to add   axr.data  as the attached data to the statement above 
                            // may have been causing the following circular ref err...
                            // 
                            //    TypeError: Converting circular structure to JSON
                            //    --> starting at object with constructor 'TLSSocket'
                            //    |     property '_httpMessage' -> object with constructor 'ClientRequest'
                            //    --- property 'socket' closes the circle
                            //    at JSON.stringify (<anonymous>)
                            //    at apiHost.<anonymous> (/app/node_modules/@codiac.io/codiac-api-base/apiCore/apiHost.js:873:49)
                            //    at Generator.next (<anonymous>)
                            //    at fulfilled (/app/node_modules/@codiac.io/codiac-api-base/apiCore/apiHost.js:11:58)
                            //    at processTicksAndRejections (internal/process/task_queues.js:97:5)
                            let statusCategory = Math.floor(axr.status / 100) * 100;
                            switch (statusCategory) {
                                case 200: { // Success codes
                                    // (We're prob not going to reach this point, since we're already in a err catch block)
                                    if (axr.headers && axr.headers.authorization)
                                        this.authToken = axr.headers.authorization;
                                    resolve([axr.data, axr.headers]);
                                    break;
                                }
                                case 300: { // Redirects and other actions
                                    resolve([axr.data, axr.headers]); //  This client should either follow or throw.  Not sure what this scenario looks like.
                                    break;
                                }
                                case 400: { // Accessibility errors
                                    if (axr.status == 404) {
                                        reject(err); // we have to throw bc we're not getting an endpoint contract back
                                    }
                                    else {
                                        resolve([axr.data, axr.headers]); // these are cases in which the endpoint is actually responding with a proper response contract.
                                    }
                                    break;
                                }
                                case 500: { // Server errors  
                                    if (axr.data) {
                                        // We cant differentiate general server processing errors from errors thrown by the endpoint. -- TODO: our api endpoints all need to return the same kind of response for errors (a standard error contract) 
                                        // TODO: The api ashould provide a header value to let us know whether it was the endpoint that responded or not.
                                        resolve([axr.data, axr.headers]);
                                        // reject(err);
                                    }
                                    else {
                                        // we have to throw bc we're not getting an endpoint contract back
                                        reject(defaultErrResponse.error); // the caller will know what type of response to provide from this point.
                                    }
                                    break;
                                }
                            }
                            resolve([axr.data, axr.headers]);
                        }
                        else if (err.isAxiosError) {
                            let fqUrl = new URL(url, this.apiRootUrl).href;
                            let newErr = new Error("No response from ".concat(fqUrl, ":", (err.code ? " [code: ".concat(err.code, "]") : ""), " ", err.message));
                            newErr.stack = err.stack;
                            this.logger.error(newErr.message, newErr);
                            reject(newErr);
                        }
                        else {
                            this.logger.error(`Error making http call: ${err.message}`, { httpVerb: httpVerb, url: url === null || url === void 0 ? void 0 : url.split("?")[0], error: err });
                            reject(err);
                        }
                    });
                }
                catch (err) {
                    reject(err);
                }
            }));
        });
    }
    /** Fires off an http request to the remote api,
     * AND RETURNS THE ENTIRE AXIOS RESPONSE.
     * Throws any encountered exceptions
     * (api exceptions dont get raised: they get passed back in the response envelope).
     *
     * @param httpVerb
     * @param url Can be relative to this.apiBaseUrl or fully qualified.
     * @param req
     * @param headers
     */
    makeRawHttpCall(httpVerb, url, req, headers) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                try {
                    this.logger.detail(`Api client making request: ${httpVerb}  ${url === null || url === void 0 ? void 0 : url.split("?")[0]}`);
                    let agent = new https.Agent({ rejectUnauthorized: false });
                    let reqHeaders = {};
                    reqHeaders["content-type"] = "application/json";
                    if (this.authToken) {
                        reqHeaders[this.tokenHeaderName] = this.authToken;
                    }
                    if (headers) {
                        for (let headerKey in headers) {
                            if (headers[headerKey])
                                reqHeaders[headerKey] = headers[headerKey];
                        }
                    }
                    let axiosOptions = {
                        "headers": reqHeaders,
                        "httpsAgent": agent
                    };
                    if (url.indexOf("://") < 0) {
                        axiosOptions.baseURL = this.apiRootUrl;
                    }
                    // TODO:  Consider a different http base library for this:
                    // https://www.npmjs.com/package/got
                    // https://www.npmjs.com/package/node-fetch
                    // let apiResponse = await axios.request<TResponse>({ ...axiosOptions, url: url, method: httpVerb, data: req });
                    return axios_1.default.request(Object.assign(Object.assign({}, axiosOptions), { url: url, method: httpVerb, data: req }))
                        .then(res => {
                        this.logger.debug(`Raw response from [${httpVerb} ${url === null || url === void 0 ? void 0 : url.split("?")[0]}] against apiRootUrl: [${this.apiRootUrl}] [status: ${res.status}  ${res.statusText}]`);
                        resolve(res);
                    })
                        .catch(err => {
                        // this.logger.debug(`Error making request [${httpVerb} ${url}] against apiRootUrl: [${this.apiRootUrl}]: ${err.message || ""}]`);
                        // reject(err);
                        // Might need to do this if axios throws on non-200s...
                        if (err.response) {
                            let axr = err.response;
                            this.logger.debug(`Remote API returned failure http status: ${axr.status || ""} ${axr.statusText || ""}.`);
                            // Trying to add   axr.data  as the attached data to the statement above 
                            // may have been causing the following circular ref err...
                            // 
                            //    TypeError: Converting circular structure to JSON
                            //    --> starting at object with constructor 'TLSSocket'
                            //    |     property '_httpMessage' -> object with constructor 'ClientRequest'
                            //    --- property 'socket' closes the circle
                            //    at JSON.stringify (<anonymous>)
                            //    at apiHost.<anonymous> (/app/node_modules/@codiac.io/codiac-api-base/apiCore/apiHost.js:873:49)
                            //    at Generator.next (<anonymous>)
                            //    at fulfilled (/app/node_modules/@codiac.io/codiac-api-base/apiCore/apiHost.js:11:58)
                            //    at processTicksAndRejections (internal/process/task_queues.js:97:5)
                            resolve(axr);
                        }
                        else if (err.isAxiosError) {
                            let fqUrl = new URL(url, this.apiRootUrl).href;
                            let newErr = new Error("No response from ".concat(fqUrl, ":", (err.code ? " [code: ".concat(err.code, "]") : ""), " ", err.message));
                            newErr.stack = err.stack;
                            this.logger.error(newErr.message, newErr);
                            reject(newErr);
                        }
                        else {
                            this.logger.error(`Error making http call: ${err.message}`, { httpVerb: httpVerb, url: url === null || url === void 0 ? void 0 : url.split("?")[0], error: err });
                            reject(err);
                        }
                    });
                }
                catch (err) {
                    this.logger.error(`Error forming http request: ${err.message}`, { httpVerb: httpVerb, url: url === null || url === void 0 ? void 0 : url.split("?")[0], error: err });
                    reject(err);
                }
            }));
        });
    }
    /** Performs replacements on the route using
     * the matching values from the given request object
     * @param route  The relative url path for the endpoint including route tokens.
     * @param applyRemainingToQuerystring  (default: false) When set, adds querystring params
     * for every property on the entity that was not already applied to a route token.
     * */
    buildUrl(route, request, applyRemainingToQuerystring = false) {
        let pattern = new urlPattern(route, { segmentValueCharset: 'a-zA-Z0-9-_~ %.@' });
        let url = pattern.stringify(request);
        // Remove the properties of the request that are
        // already tokenized in the route 
        let tokenPattern = /(?!:)\w+/gi; //  /(:[^/]\w+)/g
        let rx = new RegExp(tokenPattern, "g");
        let matches = rx.exec(route);
        let remaining = Object.assign({}, request);
        let tokens = [];
        while (matches) {
            // let tokens = matches.map(t => t.slice(1));
            tokens.push(...matches);
            // TODO:  Revisit this to remove token modifiers () 
            // This does not remove the modifiers to a token.  It assumes tokens are all in format ":property"
            remaining = this.omit(remaining, tokens);
            matches = rx.exec(route);
        }
        let qs;
        if (applyRemainingToQuerystring) {
            // By now we must already have applied any applicable serializers.
            // Whatever properties still remain unserialized are meant for the body, 
            // and cannot occur in the querystring,
            // so we dont add anything to the querystring that isnt already a primitive,
            // or this method will empty it out, eg:  "?myval="
            let natives = this.extractPrimitiveProperties(remaining);
            qs = querystring.stringify(natives);
        }
        if (qs) {
            url = url.concat("?", qs);
        }
        return url;
    }
    /** Returns an object containing only properties with primitive values;
     *  no objects, or functions.
     *
     *  NOTE:  DOES include null values (which javascript still considers objects)
     *
     * @see [The world picking up the slack on this failure](https://stackoverflow.com/questions/8511281/check-if-a-value-is-an-object-in-javascript/8511350#8511350)
     */
    extractPrimitiveProperties(remaining) {
        if (remaining == undefined)
            return undefined;
        let prim = {};
        for (let prop in remaining) {
            if (remaining[prop] === null || (typeof remaining[prop] !== 'object' && typeof remaining[prop] !== 'function')) {
                prim[prop] = remaining[prop];
            }
        }
        return prim;
    }
    /** Serializes property values of the given entity
     * whose types have a registered serializer. */
    // We dont need the generic signature, and we're not going to have it because we are recursing properties on an entity.  AND  We're converting properties to strings, so typesafety is now gone.
    // serialize<T extends any>(entity: T, serializerMap: stringDictionary): T {
    applyPropertySerializers(entity, serializerMap) {
        let output = entity;
        for (let prop in serializerMap) {
            let propType = serializerMap[prop];
            if (propType && entity[prop]) {
                let ser = ApiClientBase_1.getSerializerFor(propType);
                if (ser) {
                    output[prop] = ser.serialize(entity[prop]);
                }
            }
        }
        return output;
    }
    /** Safe to blindly append this to an existing url tat does not yet have a querystring.
     * Returns "?" character if the given obj has properties.
     * Returns "" if the given obj is undefined or empty. */
    createQueryStringFrom(obj) {
        let qs = "";
        let sep = "";
        for (let prop in obj) {
            // TODO Serialize val (if reqd, eg: StringFilter) 
            let val = querystring.escape(obj[prop]);
            qs = qs.concat(`${sep}${prop}=${val}`);
            sep = "&";
        }
        if (qs != "")
            qs = "?".concat(qs);
        return qs;
    }
    /** Creates a new object from the given object without the given property paths */
    omit(entity, paths) {
        let output = Object.assign({}, entity);
        for (let path of paths) {
            if (output[path]) {
                delete output[path];
            }
        }
        return output;
    }
    /** Very generic method for executing a POST operation against the api
     *  from an endpoint definition in the registered endpoints collection.
     *  Hydrates any route parameters or required headers for the endpoint
     *  from the given requestContract and routeValues objects.
     *  Throws any exceptions
     *  (because it cant guarantee a response envelope that declares
     *   errors and successes, it cant implement a "try" pattern).
     * @param routeValues Additional key value pairs (beyond the requestContract) to apply to any route parameters for the endpoint.
     */
    post(requestType, requestContract, routeValues) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return this.hitConfiguredEndpoint(requestType, codiac_common_1.httpRestVerb.POST, requestContract, routeValues);
        });
    }
    /** Very generic method for executing a PUT operation against the api
     *  from an endpoint definition in the registered endpoints collection.
     *  Hydrates any route parameters or required headers for the endpoint
     *  from the given requestContract and routeValues objects.
     *  Throws any exceptions
     *  (because it cant guarantee a response envelope that declares
     *   errors and successes, it cant implement a "try" pattern).
     * @param routeValues Additional key value pairs (beyond the requestContract) to apply to any route parameters for the endpoint.
     */
    put(requestType, requestContract, routeValues) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return this.hitConfiguredEndpoint(requestType, codiac_common_1.httpRestVerb.PUT, requestContract, routeValues);
        });
    }
    /** Very generic method for executing a GET operation against the api
     *  from an endpoint definition in the registered endpoints collection.
     *  Hydrates any route parameters or required headers for the endpoint
     *  from the given requestContract and routeValues objects.
     *  Throws any exceptions
     *  (because it cant guarantee a response envelope that declares
     *   errors and successes, it cant implement a "try" pattern).
     * @param routeValues Additional key value pairs (beyond the requestContract) to apply to any route parameters for the endpoint.
     */
    get(requestType, requestContract, routeValues) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return this.hitConfiguredEndpoint(requestType, codiac_common_1.httpRestVerb.GET, requestContract, routeValues);
        });
    }
    /** Very generic method for executing a PATCH operation against the api
     *  from an endpoint definition in the registered endpoints collection.
     *  Hydrates any route parameters or required headers for the endpoint
     *  from the given requestContract and routeValues objects.
     *  Throws any exceptions
     *  (because it cant guarantee a response envelope that declares
     *   errors and successes, it cant implement a "try" pattern).
     * @param routeValues Additional key value pairs (beyond the requestContract) to apply to any route parameters for the endpoint.
     */
    patch(requestType, requestContract, routeValues) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return this.hitConfiguredEndpoint(requestType, codiac_common_1.httpRestVerb.PATCH, requestContract, routeValues);
        });
    }
    /** Very generic method for executing a DELETE operation against the api
     *  from an endpoint definition in the registered endpoints collection.
     *  Hydrates any route parameters or required headers for the endpoint
     *  from the given requestContract and routeValues objects.
     *  Throws any exceptions
     *  (because it cant guarantee a response envelope that declares
     *   errors and successes, it cant implement a "try" pattern).
     * @param routeValues Additional key value pairs (beyond the requestContract) to apply to any route parameters for the endpoint.
     */
    delete(requestType, requestContract, routeValues) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return this.hitConfiguredEndpoint(requestType, codiac_common_1.httpRestVerb.DELETE, requestContract, routeValues);
        });
    }
    /** Very generic method for executing an http operation against the api
     *  from an endpoint definition in the registered endpoints collection.
     *  Hydrates any route parameters or required headers for the endpoint
     *  from the given requestContract and routeValues objects.
     *  Throws any exceptions
     *  (because it cant guarantee a response envelope that declares
     *   errors and successes, it cant implement a "try" pattern).
     * @param routeValues Additional key value pairs (beyond the requestContract) to apply to any route parameters for the endpoint.
     */
    hitConfiguredEndpoint(requestType, httpVerb, requestContract, routeValues) {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return new Promise((resolve, reject) => tslib_1.__awaiter(this, void 0, void 0, function* () {
                try {
                    let spec = this.getEndpointFor(requestType, httpVerb);
                    let headers;
                    // if (options && options.projection) {
                    //   headers = {};
                    //   headers[Hdr.PROJECTION_INCLUDES] = options.projection.pathsIncluded;
                    //   headers[Hdr.PROJECTION_EXCLUDES] = options.projection.pathsExcluded;
                    // }
                    let values = Object.assign(Object.assign({}, requestContract), routeValues);
                    let stuffIntoQuerystring = (httpVerb == codiac_common_1.httpRestVerb.GET); // Applies the whole request object to the querystring
                    let url = this.buildUrl(spec.route, values, stuffIntoQuerystring);
                    this.makeHttpCall(spec.httpMethod, url, requestContract, headers)
                        .then(result => resolve(result))
                        .catch(reason => {
                        this.logger.write(`Exception caught by client from an http ${httpVerb} of type [${(0, codiac_common_1.typeNameOf)(requestType)}]: ${reason.message || reason}`);
                        reject(reason);
                    });
                }
                catch (err) {
                    this.logger.write(`Client exception attempting to make an http ${httpVerb} of type [${(0, codiac_common_1.typeNameOf)(requestType)}]: ${err.message}`);
                    reject(err);
                }
            }));
        });
    }
};
ApiClientBase.endpointSpecs = new inversify_1.Container();
ApiClientBase.serializers = new inversify_1.Container();
/** Applied to this.tokenHeaderParam in the ctor.
 *  Typical name of the http request header that declares the authentication token for the request.  */
ApiClientBase.DEFAULT_TOKEN_HEADER_PARAM = "authorization";
ApiClientBase = ApiClientBase_1 = tslib_1.__decorate([
    (0, inversify_1.injectable)(),
    tslib_1.__param(0, (0, inversify_1.inject)(codiac_common_1.INTERFACES.ILogger)),
    tslib_1.__param(1, (0, inversify_1.unmanaged)()),
    tslib_1.__param(2, (0, inversify_1.unmanaged)()),
    tslib_1.__metadata("design:paramtypes", [Object, String, String])
], ApiClientBase);
exports.ApiClientBase = ApiClientBase;
//# sourceMappingURL=api-client-base.js.map