"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const base_path_1 = __importDefault(require("lib/base-path"));
const lru_cache_1 = __importDefault(require("lru-cache"));
const path_1 = require("path");
const VERSION = "v2";
async function apiPost(path, data, cache_s = 0 // if given, cache results for this many seconds to avoid overfetching
) {
    let cache, key;
    if (cache_s) {
        cache = getCache(cache_s);
        key = JSON.stringify({ path, data });
        if (cache.has(key)) {
            return cache.get(key);
        }
    }
    const response = await fetch((0, path_1.join)(base_path_1.default, "api", VERSION, path), {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
    });
    let result;
    try {
        result = await response.json();
        if (result.error) {
            // if error is set in response, then just through exception (this greatly simplifies client code).
            throw Error(result.error);
        }
    }
    catch (err) {
        if (response.statusText == "Not Found") {
            throw Error(`The API endpoint ${path} does not exist`);
        }
        throw err;
    }
    if (cache_s) {
        cache.set(key, result);
    }
    return result;
}
exports.default = apiPost;
const caches = {};
function getCache(seconds) {
    if (!caches[seconds]) {
        caches[seconds] = new lru_cache_1.default({
            maxAge: 1000 * seconds,
            max: 200,
        });
    }
    return caches[seconds];
}
//# sourceMappingURL=post.js.map