339 lines
		
	
	
		
			9.2 KiB
		
	
	
	
		
			JavaScript
		
	
	
	
	
	
			
		
		
	
	
			339 lines
		
	
	
		
			9.2 KiB
		
	
	
	
		
			JavaScript
		
	
	
	
	
	
//TODO: Add delete buttons for messages
 | 
						|
//TODO: Save button deactivation after swap, post or delete
 | 
						|
//TODO: It sends request, gets responds but doesnt run a function!!
 | 
						|
//TODO: Warning is displayed twice
 | 
						|
var clientUUID = '';
 | 
						|
var json = {};
 | 
						|
var jsonIndex = 0;
 | 
						|
var htable_row = 0;
 | 
						|
var host = getDomain();
 | 
						|
var dataModified = false;
 | 
						|
const C_UUID = 'mock-uuid';
 | 
						|
const setModified = function(){
 | 
						|
    setDataModified();
 | 
						|
}
 | 
						|
const setOrigin = function(){
 | 
						|
    setDataOrigin();
 | 
						|
}
 | 
						|
 | 
						|
const getUpdate = function(){
 | 
						|
    updateData();
 | 
						|
}
 | 
						|
$('#iconPlus').click(function(){addMessage()});
 | 
						|
$('#btn-addRow').click(function(){addRow()});
 | 
						|
//TODO remove later save onclick init
 | 
						|
$('#btn-save').click(getUpdate);
 | 
						|
 | 
						|
function getData(){
 | 
						|
    loadCookies();
 | 
						|
    $.getJSON(host + '/mock/json/'+clientUUID, function(data) {
 | 
						|
        json = data;
 | 
						|
        clientUUID = json[jsonIndex].clientUUID;
 | 
						|
        setCookies();
 | 
						|
        console.log(JSON.stringify(json));
 | 
						|
        console.log("Json received");
 | 
						|
        refreshData();
 | 
						|
    });
 | 
						|
}
 | 
						|
 | 
						|
function getDomain(){
 | 
						|
    var url = window.location.href;
 | 
						|
    var arr = url.split("/");
 | 
						|
    var result = arr[0] + "//" + arr[2];
 | 
						|
    return result;
 | 
						|
}
 | 
						|
 | 
						|
function setDataModified(){
 | 
						|
    if(dataModified) return;
 | 
						|
    dataModified = true;
 | 
						|
    $('#btn-save').removeClass('btn-inactive');
 | 
						|
    $('#btn-save').addClass('btn-action');
 | 
						|
    $('#btn-save').click(getUpdate);
 | 
						|
}
 | 
						|
 | 
						|
//Adding change listener to fields
 | 
						|
$('.field').change(setModified);
 | 
						|
 | 
						|
function setDataOrigin(){
 | 
						|
    dataModified = false;
 | 
						|
    $('#btn-save').addClass('btn-inactive');
 | 
						|
    $('#btn-save').removeClass('btn-action');
 | 
						|
    $('#btn-save').off();
 | 
						|
}
 | 
						|
 | 
						|
function displayDataLossWarn(){
 | 
						|
    if(dataModified) alert('Data modification lost');
 | 
						|
}
 | 
						|
 | 
						|
function refreshData(){
 | 
						|
    fillMessageList();
 | 
						|
    console.log("List initiated");
 | 
						|
    loadMessage(json[jsonIndex].mockedResponseId);
 | 
						|
    console.log("Message loaded");
 | 
						|
}
 | 
						|
 | 
						|
function setCookies(){
 | 
						|
    document.cookie = C_UUID + '=' +clientUUID+';';
 | 
						|
}
 | 
						|
 | 
						|
function loadCookies(){
 | 
						|
    clientUUID = getCookie(C_UUID);
 | 
						|
}
 | 
						|
 | 
						|
function getCookie(cname) {
 | 
						|
    var name = cname + '=';
 | 
						|
    var decodedCookie = decodeURIComponent(document.cookie);
 | 
						|
    var ca = decodedCookie.split(';');
 | 
						|
    for(var i = 0; i <ca.length; i++) {
 | 
						|
        var c = ca[i];
 | 
						|
        while (c.charAt(0) == ' ') {
 | 
						|
            c = c.substring(1);
 | 
						|
        }
 | 
						|
        if (c.indexOf(name) == 0) {
 | 
						|
            return c.substring(name.length, c.length);
 | 
						|
        }
 | 
						|
    }
 | 
						|
    return '';
 | 
						|
}
 | 
						|
 | 
						|
function displaySaveConfirmation(){
 | 
						|
    alert('message has been saved');
 | 
						|
}
 | 
						|
 | 
						|
function updateData(){
 | 
						|
    var updatedJson = generateJson();
 | 
						|
    const dataSaved = function () {
 | 
						|
        displaySaveConfirmation();
 | 
						|
        setDataOrigin();
 | 
						|
        getData();
 | 
						|
    }
 | 
						|
    var request = $.ajax({
 | 
						|
        url: host + '/mock/json',
 | 
						|
        type: 'PUT',
 | 
						|
        data: JSON.stringify(updatedJson, null, 2),
 | 
						|
        contentType: "application/json",
 | 
						|
    });
 | 
						|
    request.done(dataSaved);
 | 
						|
}
 | 
						|
 | 
						|
function addMessage(){
 | 
						|
    displayDataLossWarn();
 | 
						|
    var request = $.ajax({
 | 
						|
        url: host + '/mock/json/'+clientUUID,
 | 
						|
        type: 'POST',
 | 
						|
    });
 | 
						|
    request.done(function () {
 | 
						|
        getData();
 | 
						|
    });
 | 
						|
}
 | 
						|
 | 
						|
function removeTile(id){
 | 
						|
    displayDataLossWarn();
 | 
						|
    var jsonObject = findJsonById(id);
 | 
						|
    var request = $.ajax({
 | 
						|
        url: host + '/mock/json/'+clientUUID + '/' + id,
 | 
						|
        type: 'DELETE',
 | 
						|
    });
 | 
						|
    request.done(function () {
 | 
						|
        getData();
 | 
						|
    });
 | 
						|
}
 | 
						|
 | 
						|
 | 
						|
function clearMock(){
 | 
						|
    fillStaticFields('','','','');
 | 
						|
    htable_row = 0;
 | 
						|
    $('#httpStatusValues').html('');
 | 
						|
}
 | 
						|
 | 
						|
function initializeMock(index){
 | 
						|
    clearMock();
 | 
						|
    fillStaticFields(json[index].clientUUID
 | 
						|
        , json[index].mockedResponseId
 | 
						|
        , json[index].mediaType
 | 
						|
        , json[index].messageBody
 | 
						|
        , json[index].httpStatus);
 | 
						|
    fillHeaderTable(json[index].httpHeaders);
 | 
						|
}
 | 
						|
 | 
						|
function fillStaticFields(uuid, id, mediaType, body, httpStatus){
 | 
						|
    let link = createLink(uuid,id);
 | 
						|
    $('#messageLink').html('<a href="' + link + '" target="_blank">' + link + '</a>');
 | 
						|
    $('#httpStatus').val(httpStatus);
 | 
						|
    $('#typeSelector').val(mediaType);
 | 
						|
    $('#bodyEditor').val(body);
 | 
						|
    $('#mockedMessageId').html(id);
 | 
						|
 | 
						|
}
 | 
						|
 | 
						|
function createLink(uuid, id){
 | 
						|
    var link =  host + '/klaus/v1/get/'+uuid+'/'+id;
 | 
						|
    return link;
 | 
						|
}
 | 
						|
 | 
						|
function fillHeaderTable(headers){
 | 
						|
    var innerHTML = $('#httpStatusValues').html();
 | 
						|
    innerHTML += generateHeaderTable(headers);
 | 
						|
    $('#httpStatusValues').html(innerHTML);
 | 
						|
    $('.tableField').change(function(){setDataModified()});
 | 
						|
}
 | 
						|
//TODO: Add addRow() to generate new rows and populate them with data
 | 
						|
function generateHeaderTable(headers){
 | 
						|
    let count = 0;
 | 
						|
    let innerHTML = '';
 | 
						|
    for(var item in headers){
 | 
						|
        if( headers.hasOwnProperty(item) ) count++;
 | 
						|
    }
 | 
						|
    var keys = new Array(count);
 | 
						|
    var values = new Array(count);
 | 
						|
    let index = 0;
 | 
						|
    for(var key in Object.keys(headers)){
 | 
						|
        keys[index++]=Object.keys(headers)[key];
 | 
						|
    }
 | 
						|
    index = 0;
 | 
						|
    for(var val in headers){
 | 
						|
        values[index++]=headers[val];
 | 
						|
    }
 | 
						|
 | 
						|
    for(let i=0; i<count; i++){
 | 
						|
        innerHTML+=
 | 
						|
            '<tr id="hrow' + htable_row + '" class="httpStatusValue">' +
 | 
						|
                '<td>' +
 | 
						|
                    '<input type="text" name="headerKey" placeholder="key" class="tableField textField-key" value="' + keys[i] + '"/></td>' +
 | 
						|
                '<td>' +
 | 
						|
                    '<input type="text" name="headerValue" placeholder="value" class="tableField" value="' + values[i] + '"/></td>' +
 | 
						|
            '<td class="btn-function-table btn-table-remove" onclick="removeRow(' + htable_row + ')">X</td>' +
 | 
						|
            '</tr>';
 | 
						|
        htable_row++;
 | 
						|
    }
 | 
						|
    return innerHTML;
 | 
						|
}
 | 
						|
 | 
						|
function removeRow(row){
 | 
						|
    $('#hrow' + row).remove();
 | 
						|
    setDataModified();
 | 
						|
}
 | 
						|
 | 
						|
function addRow(){
 | 
						|
    var table = $('#httpStatusValues');
 | 
						|
    var hkey = $('#headerKeyInput');
 | 
						|
    var hval = $('#headerValueInput');
 | 
						|
    if(hkey.val() == 'key' || hkey.val() == '' || hval.val() == 'value' || hval.val() == '') return;
 | 
						|
    var innerHtml =
 | 
						|
        '<tr id="hrow' + htable_row + '" class="httpStatusValue">' +
 | 
						|
        '<td>' +
 | 
						|
        '<input " type="text" name="headerKey" placeholder="key" class="tableField textField-key" value="' + hkey.val() +
 | 
						|
        '"/></td>' +
 | 
						|
        '<td>' +
 | 
						|
        '<input " type="text" name="headerKey" placeholder="key" class="tableField" value="' + hval.val() + '"/></td>' +
 | 
						|
        '<td class="btn-function-table btn-table-remove" onclick="removeRow(' + htable_row + ')">X</td>' +
 | 
						|
        '</tr>';
 | 
						|
    htable_row++;
 | 
						|
    table.append(innerHtml);
 | 
						|
    hkey.val('');
 | 
						|
    hval.val('');
 | 
						|
    setDataModified();
 | 
						|
}
 | 
						|
 | 
						|
function fillMessageList(){
 | 
						|
    $("#listItems").html('');
 | 
						|
    var innerHTML = '';
 | 
						|
    for(let i=0; i<json.length; i++){
 | 
						|
        innerHTML += generateMessageTileHtml(json[i].mockedResponseId, json[i].httpStatus, json[i].mediaType);
 | 
						|
    }
 | 
						|
    $("#listItems").append(innerHTML);
 | 
						|
}
 | 
						|
 | 
						|
 | 
						|
//TODO: Implement methods where its possible
 | 
						|
function findJsonById(id){
 | 
						|
    return json[findJsonIndexById(id)];
 | 
						|
}
 | 
						|
 | 
						|
function findJsonIndexById(id){
 | 
						|
    for(let i=0; i<json.length; i++)
 | 
						|
        if(id == json[i].mockedResponseId) return i;
 | 
						|
}
 | 
						|
 | 
						|
function loadMessage(id){
 | 
						|
    displayDataLossWarn();
 | 
						|
    setDataOrigin();
 | 
						|
    for(let i=0; i<json.length; i++){
 | 
						|
        if(id == json[i].mockedResponseId){
 | 
						|
            jsonIndex = i;
 | 
						|
            console.log("Message found");
 | 
						|
            initializeMock(jsonIndex);
 | 
						|
            console.log("Fields initialized");
 | 
						|
            selectMessage(id);
 | 
						|
            console.log("Selection complete");
 | 
						|
            return;
 | 
						|
        }
 | 
						|
    }
 | 
						|
    console.log("Message not found");
 | 
						|
}
 | 
						|
 | 
						|
function selectMessage(id){
 | 
						|
    console.log("Selecting message...");
 | 
						|
    $(".menuItemSelected").on("click");
 | 
						|
    $(".menuItemSelected").addClass("menuItem");
 | 
						|
    $(".menuItemSelected").removeClass("menuItemSelected");
 | 
						|
    console.log("Selected message deselected");
 | 
						|
    let itemId = '#item_'+id;
 | 
						|
    $(itemId).off("click");
 | 
						|
    $(itemId).addClass("menuItemSelected");
 | 
						|
    $(itemId).removeClass("menuItem");
 | 
						|
    console.log("Selected message selected");
 | 
						|
}
 | 
						|
 | 
						|
function generateMessageTileHtml(id, httpStatus, mediaType){
 | 
						|
    var innerHTML = '<div class="menuItem" id="item_' + id + '" onclick="loadMessage('+ id +')">' +
 | 
						|
        '<table><tr><td>Id: '+ id +'</td></tr>' +
 | 
						|
        '<tr><td>Http-status: '+ httpStatus +'</td></tr>' +
 | 
						|
        '</table></div><div class="btn-del-MenuItem" onclick="removeTile(' + id + ')">X</div>' +
 | 
						|
        '<div style="clear: both;"></div>';
 | 
						|
    return innerHTML;
 | 
						|
}
 | 
						|
 | 
						|
 | 
						|
 | 
						|
function onbuild(){
 | 
						|
    getData();
 | 
						|
    sleep(1000);
 | 
						|
}
 | 
						|
 | 
						|
$(document).ready(onbuild());
 | 
						|
 | 
						|
function sleep(ms) {
 | 
						|
    return new Promise(resolve => setTimeout(resolve, ms));
 | 
						|
}
 | 
						|
 | 
						|
 | 
						|
 | 
						|
function generateJson(){
 | 
						|
    var newJson =
 | 
						|
        {
 | 
						|
            clientUUID: json[jsonIndex].clientUUID,
 | 
						|
            mockedResponseId: json[jsonIndex].mockedResponseId,
 | 
						|
            mediaType: $('#typeSelector').val(),
 | 
						|
            messageBody: $('#bodyEditor').val(),
 | 
						|
            httpStatus: $('#httpStatus').val(),
 | 
						|
            httpHeaders: {},
 | 
						|
        };
 | 
						|
    newJson['httpHeaders'] = convertTableToJson();
 | 
						|
    console.log(JSON.stringify(newJson, null, 2));
 | 
						|
    json[jsonIndex] = newJson;
 | 
						|
    return newJson;
 | 
						|
}
 | 
						|
 | 
						|
 | 
						|
function convertTableToJson(){
 | 
						|
    var rows = $('.httpStatusValue');
 | 
						|
    console.log("Rows: "+rows.length);
 | 
						|
    var obj = {};
 | 
						|
    var key;
 | 
						|
    for(let i=0; i<rows.length; i++){
 | 
						|
        key = rows.eq(i).children().eq(0).children().eq(0).val();
 | 
						|
        obj[key] = rows.eq(i).children().eq(1).children().eq(0).val();
 | 
						|
    }
 | 
						|
    return obj;
 | 
						|
} |