aboutsummaryrefslogtreecommitdiffstats
path: root/apidoc/utils
diff options
context:
space:
mode:
authorAdrien Hopkins <[email protected]>2021-08-18 13:45:18 -0500
committerAdrien Hopkins <[email protected]>2021-08-18 13:45:18 -0500
commite4669eaf9700ecc503bee3305315256968bd05e5 (patch)
treefd5955fc3450351f80eb64221faca0854412612b /apidoc/utils
parent01b96b95507d6ffd6c551c834bea5478b190d308 (diff)
downloadcoinos-server-e4669eaf9700ecc503bee3305315256968bd05e5.tar.gz
coinos-server-e4669eaf9700ecc503bee3305315256968bd05e5.zip
Compiled existing api docs to ./apidoc/
Diffstat (limited to 'apidoc/utils')
-rw-r--r--apidoc/utils/handlebars_helper.js416
-rw-r--r--apidoc/utils/send_sample_request.js272
-rw-r--r--apidoc/utils/send_sample_request_utils.js97
3 files changed, 785 insertions, 0 deletions
diff --git a/apidoc/utils/handlebars_helper.js b/apidoc/utils/handlebars_helper.js
new file mode 100644
index 00000000..ed1dc1da
--- /dev/null
+++ b/apidoc/utils/handlebars_helper.js
@@ -0,0 +1,416 @@
+define([
+ 'locales',
+ 'handlebars',
+ 'diffMatchPatch'
+], function(locale, Handlebars, DiffMatchPatch) {
+
+ /**
+ * Return a text as markdown.
+ * Currently only a little helper to replace apidoc-inline Links (#Group:Name).
+ * Should be replaced with a full markdown lib.
+ * @param string text
+ */
+ Handlebars.registerHelper('markdown', function(text) {
+ if ( ! text ) {
+ return text;
+ }
+ text = text.replace(/((\[(.*?)\])?\(#)((.+?):(.+?))(\))/mg, function(match, p1, p2, p3, p4, p5, p6) {
+ var link = p3 || p5 + '/' + p6;
+ return '<a href="#api-' + p5 + '-' + p6 + '">' + link + '</a>';
+ });
+ return text;
+ });
+
+ /**
+ * set paramater type.
+ */
+ Handlebars.registerHelper("setInputType", function(text) {
+ if (text === "File") {
+ return "file";
+ }
+ return "text";
+ });
+
+ /**
+ * start/stop timer for simple performance check.
+ */
+ var timer;
+ Handlebars.registerHelper('startTimer', function(text) {
+ timer = new Date();
+ return '';
+ });
+
+ Handlebars.registerHelper('stopTimer', function(text) {
+ console.log(new Date() - timer);
+ return '';
+ });
+
+ /**
+ * Return localized Text.
+ * @param string text
+ */
+ Handlebars.registerHelper('__', function(text) {
+ return locale.__(text);
+ });
+
+ /**
+ * Console log.
+ * @param mixed obj
+ */
+ Handlebars.registerHelper('cl', function(obj) {
+ console.log(obj);
+ return '';
+ });
+
+ /**
+ * Replace underscore with space.
+ * @param string text
+ */
+ Handlebars.registerHelper('underscoreToSpace', function(text) {
+ return text.replace(/(_+)/g, ' ');
+ });
+
+ /**
+ *
+ */
+ Handlebars.registerHelper('assign', function(name) {
+ if(arguments.length > 0) {
+ var type = typeof(arguments[1]);
+ var arg = null;
+ if(type === 'string' || type === 'number' || type === 'boolean') arg = arguments[1];
+ Handlebars.registerHelper(name, function() { return arg; });
+ }
+ return '';
+ });
+
+ /**
+ *
+ */
+ Handlebars.registerHelper('nl2br', function(text) {
+ return _handlebarsNewlineToBreak(text);
+ });
+
+ /**
+ *
+ */
+ Handlebars.registerHelper('if_eq', function(context, options) {
+ var compare = context;
+ // Get length if context is an object
+ if (context instanceof Object && ! (options.hash.compare instanceof Object))
+ compare = Object.keys(context).length;
+
+ if (compare === options.hash.compare)
+ return options.fn(this);
+
+ return options.inverse(this);
+ });
+
+ /**
+ *
+ */
+ Handlebars.registerHelper('if_gt', function(context, options) {
+ var compare = context;
+ // Get length if context is an object
+ if (context instanceof Object && ! (options.hash.compare instanceof Object))
+ compare = Object.keys(context).length;
+
+ if(compare > options.hash.compare)
+ return options.fn(this);
+
+ return options.inverse(this);
+ });
+
+ /**
+ *
+ */
+ var templateCache = {};
+ Handlebars.registerHelper('subTemplate', function(name, sourceContext) {
+ if ( ! templateCache[name])
+ templateCache[name] = Handlebars.compile($('#template-' + name).html());
+
+ var template = templateCache[name];
+ var templateContext = $.extend({}, this, sourceContext.hash);
+ return new Handlebars.SafeString( template(templateContext) );
+ });
+
+ /**
+ *
+ */
+ Handlebars.registerHelper('toLowerCase', function(value) {
+ return (value && typeof value === 'string') ? value.toLowerCase() : '';
+ });
+
+ /**
+ *
+ */
+ Handlebars.registerHelper('splitFill', function(value, splitChar, fillChar) {
+ var splits = value.split(splitChar);
+ return new Array(splits.length).join(fillChar) + splits[splits.length - 1];
+ });
+
+ /**
+ * Convert Newline to HTML-Break (nl2br).
+ *
+ * @param {String} text
+ * @returns {String}
+ */
+ function _handlebarsNewlineToBreak(text) {
+ return ('' + text).replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + '<br>' + '$2');
+ }
+
+ /**
+ *
+ */
+ Handlebars.registerHelper('each_compare_list_field', function(source, compare, options) {
+ var fieldName = options.hash.field;
+ var newSource = [];
+ if (source) {
+ source.forEach(function(entry) {
+ var values = entry;
+ values['key'] = entry[fieldName];
+ newSource.push(values);
+ });
+ }
+
+ var newCompare = [];
+ if (compare) {
+ compare.forEach(function(entry) {
+ var values = entry;
+ values['key'] = entry[fieldName];
+ newCompare.push(values);
+ });
+ }
+ return _handlebarsEachCompared('key', newSource, newCompare, options);
+ });
+
+ /**
+ *
+ */
+ Handlebars.registerHelper('each_compare_keys', function(source, compare, options) {
+ var newSource = [];
+ if (source) {
+ var sourceFields = Object.keys(source);
+ sourceFields.forEach(function(name) {
+ var values = {};
+ values['value'] = source[name];
+ values['key'] = name;
+ newSource.push(values);
+ });
+ }
+
+ var newCompare = [];
+ if (compare) {
+ var compareFields = Object.keys(compare);
+ compareFields.forEach(function(name) {
+ var values = {};
+ values['value'] = compare[name];
+ values['key'] = name;
+ newCompare.push(values);
+ });
+ }
+ return _handlebarsEachCompared('key', newSource, newCompare, options);
+ });
+
+ /**
+ *
+ */
+ Handlebars.registerHelper('gen_body', function(context, options) {
+ let strBody = {};
+ context.forEach(element => {
+ element.field = element.field.replace("]", "");
+ switch (element.type.toLowerCase()) {
+ case "string":
+ if (element.field.includes('[')) {
+ if (strBody[element.field.split("[")[0]] === undefined) {
+ strBody[element.field.split("[")[0]] = {};
+ }
+ strBody[element.field.split("[")[0]][element.field.split("[")[1]] = (element.defaultValue || "");
+ break;
+ }
+ strBody[element.field] = (element.defaultValue || "");
+ break;
+ case "number":
+ if (element.field.includes('[')) {
+ if (strBody[element.field.split("[")[0]] === undefined) {
+ strBody[element.field.split("[")[0]] = {};
+ }
+ strBody[element.field.split("[")[0]][element.field.split("[")[1]] = (element.defaultValue || 0);
+ break;
+ }
+ strBody[element.field] = (element.defaultValue || 0);
+ break;
+ case "object":
+ if (strBody[element.field] === undefined) {
+ strBody[element.field] = {};
+ }
+ break;
+ default:
+ strBody[element.field] = null;
+ }
+ });
+ return JSON.stringify(strBody, null, 4);
+ });
+
+ /**
+ *
+ */
+ Handlebars.registerHelper('each_compare_field', function(source, compare, options) {
+ return _handlebarsEachCompared('field', source, compare, options);
+ });
+
+ /**
+ *
+ */
+ Handlebars.registerHelper('each_compare_title', function(source, compare, options) {
+ return _handlebarsEachCompared('title', source, compare, options);
+ });
+
+ /**
+ *
+ */
+ Handlebars.registerHelper('reformat', function(source, type){
+ if (type == 'json')
+ try {
+ return JSON.stringify(JSON.parse(source.trim()),null, " ");
+ } catch(e) {
+
+ }
+ return source
+ });
+
+ /**
+ *
+ */
+ Handlebars.registerHelper('showDiff', function(source, compare, options) {
+ var ds = '';
+ if(source === compare) {
+ ds = source;
+ } else {
+ if( ! source)
+ return compare;
+
+ if( ! compare)
+ return source;
+
+ var d = diffMatchPatch.diff_main(stripHtml(compare), stripHtml(source));
+ diffMatchPatch.diff_cleanupSemantic(d);
+ ds = diffMatchPatch.diff_prettyHtml(d);
+ ds = ds.replace(/&para;/gm, '');
+ }
+ if(options === 'nl2br')
+ ds = _handlebarsNewlineToBreak(ds);
+
+ return ds;
+ });
+
+ /**
+ *
+ */
+ function _handlebarsEachCompared(fieldname, source, compare, options)
+ {
+ var dataList = [];
+ var index = 0;
+ if(source) {
+ source.forEach(function(sourceEntry) {
+ var found = false;
+ if (compare) {
+ compare.forEach(function(compareEntry) {
+ if(sourceEntry[fieldname] === compareEntry[fieldname]) {
+ var data = {
+ typeSame: true,
+ source: sourceEntry,
+ compare: compareEntry,
+ index: index
+ };
+ dataList.push(data);
+ found = true;
+ index++;
+ }
+ });
+ }
+ if ( ! found) {
+ var data = {
+ typeIns: true,
+ source: sourceEntry,
+ index: index
+ };
+ dataList.push(data);
+ index++;
+ }
+ });
+ }
+
+ if (compare) {
+ compare.forEach(function(compareEntry) {
+ var found = false;
+ if (source) {
+ source.forEach(function(sourceEntry) {
+ if(sourceEntry[fieldname] === compareEntry[fieldname])
+ found = true;
+ });
+ }
+ if ( ! found) {
+ var data = {
+ typeDel: true,
+ compare: compareEntry,
+ index: index
+ };
+ dataList.push(data);
+ index++;
+ }
+ });
+ }
+
+ var ret = '';
+ var length = dataList.length;
+ for (var index in dataList) {
+ if(index == (length - 1))
+ dataList[index]['_last'] = true;
+ ret = ret + options.fn(dataList[index]);
+ }
+ return ret;
+ }
+
+ var diffMatchPatch = new DiffMatchPatch();
+
+ /**
+ * Overwrite Colors
+ */
+ DiffMatchPatch.prototype.diff_prettyHtml = function(diffs) {
+ var html = [];
+ var pattern_amp = /&/g;
+ var pattern_lt = /</g;
+ var pattern_gt = />/g;
+ var pattern_para = /\n/g;
+ for (var x = 0; x < diffs.length; x++) {
+ var op = diffs[x][0]; // Operation (insert, delete, equal)
+ var data = diffs[x][1]; // Text of change.
+ var text = data.replace(pattern_amp, '&amp;').replace(pattern_lt, '&lt;')
+ .replace(pattern_gt, '&gt;').replace(pattern_para, '&para;<br>');
+ switch (op) {
+ case DIFF_INSERT:
+ html[x] = '<ins>' + text + '</ins>';
+ break;
+ case DIFF_DELETE:
+ html[x] = '<del>' + text + '</del>';
+ break;
+ case DIFF_EQUAL:
+ html[x] = '<span>' + text + '</span>';
+ break;
+ }
+ }
+ return html.join('');
+ };
+
+ /**
+ * Fixes html after comparison (#506, #538, #616, #825)
+ */
+ function stripHtml(html){
+ var div = document.createElement("div");
+ div.innerHTML = html;
+ return div.textContent || div.innerText || "";
+ }
+
+ // Exports
+ return Handlebars;
+});
diff --git a/apidoc/utils/send_sample_request.js b/apidoc/utils/send_sample_request.js
new file mode 100644
index 00000000..4d695d14
--- /dev/null
+++ b/apidoc/utils/send_sample_request.js
@@ -0,0 +1,272 @@
+define([
+ 'jquery',
+ 'lodash',
+ './utils/send_sample_request_utils'
+], function($, _, utils) {
+
+ var initDynamic = function() {
+ // Button send
+ $(".sample-request-send").off("click");
+ $(".sample-request-send").on("click", function(e) {
+ e.preventDefault();
+ var $root = $(this).parents("article");
+ var group = $root.data("group");
+ var name = $root.data("name");
+ var version = $root.data("version");
+ sendSampleRequest(group, name, version, $(this).data("sample-request-type"));
+ });
+
+ // Button clear
+ $(".sample-request-clear").off("click");
+ $(".sample-request-clear").on("click", function(e) {
+ e.preventDefault();
+ var $root = $(this).parents("article");
+ var group = $root.data("group");
+ var name = $root.data("name");
+ var version = $root.data("version");
+ clearSampleRequest(group, name, version);
+ });
+ }; // initDynamic
+
+ function sendSampleRequest(group, name, version, type)
+ {
+ var $root = $('article[data-group="' + group + '"][data-name="' + name + '"][data-version="' + version + '"]');
+
+ // Optional header
+ var header = {};
+ $root.find(".sample-request-header:checked").each(function(i, element) {
+ var group = $(element).data("sample-request-header-group-id");
+ $root.find("[data-sample-request-header-group=\"" + group + "\"]").each(function(i, element) {
+ var key = $(element).data("sample-request-header-name");
+ var value = element.value;
+ if (typeof element.optional === 'undefined') {
+ element.optional = true;
+ }
+ if ( ! element.optional && element.defaultValue !== '') {
+ value = element.defaultValue;
+ }
+ header[key] = value;
+ });
+ });
+
+
+ // create JSON dictionary of parameters
+ var param = {};
+ var paramType = {};
+ var bodyFormData = new FormData();
+ var bodyJson = '';
+ $root.find(".sample-request-param:checked").each(function(i, element) {
+ var group = $(element).data("sample-request-param-group-id");
+ var contentType = $(element).nextAll('.sample-header-content-type-switch').first().val();
+ if (contentType == "body-json"){
+ $root.find("[data-sample-request-body-group=\"" + group + "\"]").not(function(){
+ return $(this).val() == "" && $(this).is("[data-sample-request-param-optional='true']");
+ }).each(function(i, element) {
+ if (isJson(element.value)){
+ header['Content-Type'] = 'application/json';
+ bodyJson = element.value;
+ }
+ });
+ }else {
+ $root.find("[data-sample-request-param-group=\"" + group + "\"]").not(function(){
+ return $(this).val() == "" && $(this).is("[data-sample-request-param-optional='true']");
+ }).each(function(i, element) {
+ var key = $(element).data("sample-request-param-name");
+ var value = element.value;
+ if ( ! element.optional && element.defaultValue !== '') {
+ value = element.defaultValue;
+ }
+ if (contentType == "body-form-data"){
+ header['Content-Type'] = 'multipart/form-data'
+ if (element.type == "file") {
+ value = element.files[0];
+ }
+ bodyFormData.append(key,value);
+ }else {
+ param[key] = value;
+ paramType[key] = $(element).next().text();
+ }
+ });
+ }
+ });
+
+ // grab user-inputted URL
+ var url = $root.find(".sample-request-url").val();
+
+ //Convert {param} form to :param
+ url = utils.convertPathParams(url);
+
+ // Insert url parameter
+ var pattern = pathToRegexp(url, null);
+ var matches = pattern.exec(url);
+ for (var i = 1; i < matches.length; i++) {
+ var key = matches[i].substr(1);
+ var optional = false
+ if (key[key.length - 1] === '?') {
+ optional = true;
+ key = key.substr(0, key.length - 1);
+ }
+ if (param[key] !== undefined) {
+ url = url.replace(matches[i], encodeURIComponent(param[key]));
+
+ // remove URL parameters from list
+ delete param[key];
+ } else if (optional) {
+ // if parameter is optional denoted by ending '?' in param (:param?)
+ // and no parameter is given, replace parameter with empty string instead
+ url = url.replace(matches[i], '');
+ delete param[key];
+ }
+ } // for
+
+ //handle nested objects and parsing fields
+ param = utils.handleNestedAndParsingFields(param, paramType);
+
+ //add url search parameter
+ if (header['Content-Type'] == 'application/json') {
+ if (bodyJson) {
+ // bodyJson is set to value if request body: 'body/json' was selected and manual json was input
+ // in this case, use the given bodyJson and add other params in query string
+ url = url + encodeSearchParams(param);
+ param = bodyJson;
+ } else {
+ // bodyJson not set, but Content-Type: application/json header was set. In this case, send parameters
+ // as JSON body. First, try parsing fields of object with given paramType definition so that the json
+ // is valid against the parameter spec (e.g. Boolean params are boolean instead of strings in final json)
+ param = utils.tryParsingWithTypes(param, paramType);
+ param = JSON.stringify(param);
+ }
+ }else if (header['Content-Type'] == 'multipart/form-data'){
+ url = url + encodeSearchParams(param);
+ param = bodyFormData;
+ }
+
+ $root.find(".sample-request-response").fadeTo(250, 1);
+ $root.find(".sample-request-response-json").html("Loading...");
+ refreshScrollSpy();
+
+ // send AJAX request, catch success or error callback
+ var ajaxRequest = {
+ url : url,
+ headers : header,
+ data : param,
+ type : type.toUpperCase(),
+ success : displaySuccess,
+ error : displayError
+ };
+
+ if(header['Content-Type'] == 'multipart/form-data'){
+ delete ajaxRequest.headers['Content-Type'];
+ ajaxRequest.contentType=false;
+ ajaxRequest.processData=false;
+ }
+ $.ajax(ajaxRequest);
+
+
+ function displaySuccess(data, status, jqXHR) {
+ var jsonResponse;
+ try {
+ jsonResponse = JSON.parse(jqXHR.responseText);
+ jsonResponse = JSON.stringify(jsonResponse, null, 4);
+ } catch (e) {
+ jsonResponse = jqXHR.responseText;
+ }
+ $root.find(".sample-request-response-json").text(jsonResponse);
+ refreshScrollSpy();
+ };
+
+ function displayError(jqXHR, textStatus, error) {
+ var message = "Error " + jqXHR.status + ": " + error;
+ var jsonResponse;
+ try {
+ jsonResponse = JSON.parse(jqXHR.responseText);
+ jsonResponse = JSON.stringify(jsonResponse, null, 4);
+ } catch (e) {
+ jsonResponse = jqXHR.responseText;
+ }
+
+ if (jsonResponse)
+ message += "\n" + jsonResponse;
+
+ // flicker on previous error to make clear that there is a new response
+ if($root.find(".sample-request-response").is(":visible"))
+ $root.find(".sample-request-response").fadeTo(1, 0.1);
+
+ $root.find(".sample-request-response").fadeTo(250, 1);
+ $root.find(".sample-request-response-json").text(message);
+ refreshScrollSpy();
+ };
+ }
+
+ function clearSampleRequest(group, name, version)
+ {
+ var $root = $('article[data-group="' + group + '"][data-name="' + name + '"][data-version="' + version + '"]');
+
+ // hide sample response
+ $root.find(".sample-request-response-json").html("");
+ $root.find(".sample-request-response").hide();
+
+ // reset value of parameters
+ $root.find(".sample-request-param").each(function(i, element) {
+ element.value = "";
+ });
+
+ // restore default URL
+ var $urlElement = $root.find(".sample-request-url");
+ $urlElement.val($urlElement.prop("defaultValue"));
+
+ refreshScrollSpy();
+ }
+
+ function refreshScrollSpy()
+ {
+ $('[data-spy="scroll"]').each(function () {
+ $(this).scrollspy("refresh");
+ });
+ }
+
+ function escapeHtml(str) {
+ var div = document.createElement("div");
+ div.appendChild(document.createTextNode(str));
+ return div.innerHTML;
+ }
+
+
+ /**
+ * is Json
+ */
+ function isJson(str) {
+ if (typeof str == 'string') {
+ try {
+ var obj=JSON.parse(str);
+ if(typeof obj == 'object' && obj ){
+ return true;
+ }else{
+ return false;
+ }
+ } catch(e) {
+ return false;
+ }
+ }
+ }
+
+ /**
+ * encode Search Params
+ */
+ function encodeSearchParams(obj) {
+ const params = [];
+ Object.keys(obj).forEach((key) => {
+ let value = obj[key];
+ params.push([key, encodeURIComponent(value)].join('='));
+ })
+ return params.length === 0 ? '' : '?' + params.join('&');
+ }
+
+ /**
+ * Exports.
+ */
+ return {
+ initDynamic: initDynamic
+ };
+
+});
diff --git a/apidoc/utils/send_sample_request_utils.js b/apidoc/utils/send_sample_request_utils.js
new file mode 100644
index 00000000..fbda1ffd
--- /dev/null
+++ b/apidoc/utils/send_sample_request_utils.js
@@ -0,0 +1,97 @@
+//this block is used to make this module works with Node (CommonJS module format)
+if (typeof define !== 'function') {
+ var define = require('amdefine')(module)
+}
+
+define(['lodash'], function (_) {
+
+ var log = console;
+
+ function handleNestedFields(object, key, params, paramType) {
+ var attributes = key.split('.');
+ var field = attributes[0];
+ params.push(field);
+ if (attributes.length > 1 && paramType[params.join('.')] == 'Object') {
+ var nestedField = attributes.slice(1).join('.');
+ if (!object[field])
+ object[field] = {};
+ if (typeof object[field] == 'object') {
+ object[field][nestedField] = object[key];
+ delete object[key];
+ handleNestedFields(object[field], nestedField, params, paramType);
+ }
+ }
+ }
+
+ function handleNestedFieldsForAllParams(param, paramType) {
+ var result = Object.assign({}, param);
+ Object.keys(result).forEach(function (key) {
+ handleNestedFields(result, key, [], paramType);
+ });
+ return result
+ }
+
+ function handleArraysAndObjectFields(param, paramType) {
+ var result = Object.assign({}, param);
+ Object.keys(paramType).forEach(function (key) {
+ if (result[key] && (paramType[key].endsWith('[]') || paramType[key] === 'Object')) {
+ try {
+ result[key] = JSON.parse(result[key]);
+ } catch (e) {;}
+ }
+ });
+ return result
+ }
+
+ function tryParsingAsType(object, path, type) {
+ var val = _.get(object, path);
+ if (val !== undefined) {
+ if (type === 'Boolean') {
+ if (val === 'true') {
+ _.set(object, path, true);
+ } else if (val === 'false') {
+ _.set(object, path, false);
+ } else {
+ log.warn('Failed to parse object value at path [' + path + ']. Value: (' + val + '). Type: (' + type + ')');
+ }
+ } else if (type === 'Number') {
+ var parsedInt = parseInt(val, 10);
+ if (!_.isNaN(parsedInt)) {
+ _.set(object, path, parsedInt);
+ } else {
+ log.warn('Failed to parse object value at path [' + path + ']. Value: (' + val + '). Type: (' + type + ')');
+ }
+ }
+ }
+ }
+
+ function handleNestedAndParsingFields(param, paramType) {
+ var result = handleArraysAndObjectFields(param, paramType);
+ result = handleNestedFieldsForAllParams(result, paramType);
+ return result;
+ }
+
+ function tryParsingWithTypes(param, paramType) {
+ var result = Object.assign({}, param);
+ Object.keys(paramType).forEach(function (key) {
+ tryParsingAsType(result, key, paramType[key]);
+ });
+ return result;
+ }
+
+ // Converts path params in the {param} format to the accepted :param format, used before inserting the URL params.
+ function convertPathParams(url) {
+ return url.replace(/{(.+?)}/g, ':$1');
+ }
+
+ function setLogger(logger) {
+ log = logger;
+ }
+
+ return {
+ handleNestedAndParsingFields,
+ convertPathParams,
+ tryParsingWithTypes,
+ setLogger
+ };
+});