Skip to content
Snippets Groups Projects
datasets.js 1.60 KiB
/*global ks_global*/

/**
 * Uses the fetch API to create an ajax call for the WordPress API to fetch/post data from/to the server.
 * @param data {FormData} Data for the ajax call. Must contain an entry which specifies the ajax `action`
 * @returns {Promise<any>} The response from the server
 */
function ajaxCall(data) {
    let opts = {
        method: "POST",
        body: data,
    };

    return fetch(ks_global.ajax_url, opts).then(function (response) {
        return response.json();
    });
}

/**
 * Returns the json object from the stored graph as promise.
 *
 * @param {String} spaceId Identification of graph to load.
 *
 * @returns Promise returning graph object.
 */
export function loadGraphJson(spaceId) {
    const data = new FormData();
    data.append("action", "get_space");
    data.append("space", spaceId);

    return ajaxCall(data);
}

/**
 * Takes the graph json object and stores it in the backend.
 *
 * @param {String} spaceId Identification of graph to save.
 * @param {object} json Graph object
 *
 * @returns Promise returning state of query.
 */
export function saveGraphJson(spaceId, json) {
    const data = new FormData();
    data.append("action", "update_space");
    data.append("space", spaceId);
    data.append("graph", JSON.stringify(json));

    return ajaxCall(data);
}

/**
 * Retrieves a list of all available spaces to choose from.
 *
 * @returns A promise containing an array containing all available space ids.
 */
export function listAllSpaces() {
    const data = new FormData();
    data.append("action", "list_spaces");

    return ajaxCall(data).then((data) => data.spaces);
}