import dcopy from 'deep-copy';
import sanitizer from '../../_shared/utils/sanitizer';
import BasePatcherApiConsumer from '../base-patcher-api-consumer/base-patcher-api-consumer';
export default class EndpointPatcherApiConsumer extends BasePatcherApiConsumer {
    constructor({ baseUrl, instance }, params = {}) {
        super(params);
        this.instance = instance;
        this.baseUrl = baseUrl;
        if (params.nestedUrl)
            this.nestedUrl = params.nestedUrl;
    }
    patchItem({ id, changes }, afterUrl) {
        let updUrl = `${this.baseUrl}/${id}`;
        if (afterUrl)
            updUrl += `/${afterUrl}`;
        let changesCopy = dcopy(changes);
        if (this.preRequestHandler) {
            changesCopy = this.preRequestHandler(changesCopy);
        }
        if (this.fieldsToSend) {
            changesCopy = sanitizer(changesCopy, this.fieldsToSend);
        }
        return this._patchItem(changesCopy, updUrl);
    }
    patchNestedItem({ parentId, id, changes, afterUrl }) {
        let updUrl = `${this.baseUrl}/${parentId}/${this.nestedUrl}/${id}`;
        if (afterUrl)
            updUrl += `/${afterUrl}`;
        let changesCopy = dcopy(changes);
        if (this.preRequestHandler) {
            changesCopy = this.preRequestHandler(changesCopy);
        }
        if (this.fieldsToSend) {
            changesCopy = sanitizer(changesCopy, this.fieldsToSend);
        }
        return this._patchItem(changes, updUrl);
    }
    async _patchItem(changes, baseUrl = this.baseUrl) {
        try {
            const response = await this.instance.patch(baseUrl, changes);
            return response;
        }
        catch (err) {
            throw err;
        }
    }
}
//# sourceMappingURL=endpoint-patcher-api-consumer.js.map