Passed
Push — master ( cddcf6...1d3855 )
by Alexander
01:59
created

tcms/static/js/jsonrpc.js (1 issue)

1
// JSON-RPC client inspired by
2
// https://stackoverflow.com/questions/8147211/jquery-jsonrpc-2-0-call-via-ajax-gets-correct-response-but-does-not-work
3
function jsonRPC(rpc_method, rpc_params, callback, is_sync) {
4
   // .filter() args are passed as dictionary but other args,
5
   // e.g. for .add_tag() are passed as a list of positional values
6
   if (!Array.isArray(rpc_params)) {
7
      rpc_params = [rpc_params]
8
   }
9
10
   $.ajax({
11
      url: '/json-rpc/',
12
      async: is_sync !== true,
13
      data: JSON.stringify({jsonrpc: '2.0',
14
                            method: rpc_method,
15
                            params: rpc_params,
16
                            id:"jsonrpc"}),  // id is needed !!
17
      // see "Request object" at https://www.jsonrpc.org/specification
18
      type:"POST",
19
      dataType:"json",
20
      contentType: "application/json",
21
      success: function (result) {
22
            callback(result.result);
23
      },
24
      error: function (err,status,thrown) {
25
             console.log("*** jsonRPC ERROR: " + err + " STATUS: " + status + " " + thrown );
0 ignored issues
show
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
26
      },
27
   });
28
}
29
30
31
// used by DataTables to convert a list of objects to a dict
32
// suitable for loading data into the table
33
function dataTableJsonRPC(rpc_method, rpc_params, callback, pre_process_data) {
34
    var internal_callback = function(data) {
35
        // used to collect additional information about columns via ForeignKeys
36
        if (pre_process_data !== undefined) {
37
            pre_process_data(data);
38
        }
39
        callback({'data': data})
40
    };
41
42
    jsonRPC(rpc_method, rpc_params, internal_callback);
43
}
44
45
46
// called from pre_process_data to fill local cache with values
47
function addResourceToData(element, key, resource, cache) {
48
    var data = [];
49
    element[key].forEach(function(id) {
50
        if (id in cache) {
51
            data.push(cache[id]);
52
        } else {
53
            jsonRPC(resource, {pk: id}, function (result) {
54
                if (result) {
55
                    data.push(result[0]);
56
                    cache[id] = result[0];
57
                }
58
            }, true);
59
        }
60
    });
61
    element[key] = data;
62
}
63
64
65
// renders values from the local cache
66
// for example tags or components
67
function renderFromCache(data) {
68
    result = '';
69
    data.forEach(function (el) {
70
        result += el.name + ', ';
71
    });
72
    // remove trailing coma
73
    return result.slice(0, result.lastIndexOf(','));
74
}
75