var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { md5 } from '../../md5/md5';
export class FetchService {
    constructor(app) {
        this.app = app;
    }
    fetch(input, init, meta = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            const { json = true, cacheTime = 0, cacheKey } = meta;
            // get data
            return this.app.Cache.getRefresh('fetch_' + (!!cacheKey ? cacheKey : md5(input)), cacheTime, () => __awaiter(this, void 0, void 0, function* () {
                const response = yield fetch(input, init);
                if (!response.ok) {
                    throw new Error('API fetch failed.');
                }
                // get result
                let result;
                if (json) {
                    result = yield response.json();
                }
                else {
                    result = yield response.text();
                }
                return result;
            }));
        });
    }
    get(url, init, meta = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.fetch(url, Object.assign({}, init, { method: 'GET' }), meta);
        });
    }
    post(url, init, meta = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.fetch(url, Object.assign({}, init, { method: 'POST' }), meta);
        });
    }
    put(url, init, meta = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.fetch(url, Object.assign({}, init, { method: 'PUT' }), meta);
        });
    }
    patch(url, init, meta = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.fetch(url, Object.assign({}, init, { method: 'PATCH' }), meta);
        });
    }
    delete(url, init, meta = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.fetch(url, Object.assign({}, init, { method: 'DELETE' }), meta);
        });
    }
}
