any2api-generator-rest
Version:
REST API implementation generator for any2api
1,531 lines (1,229 loc) • 206 kB
JavaScript
(function (window) {
'use strict';
// Namespaces
RAML.Directives = {};
RAML.Services = {};
RAML.Filters = {};
RAML.Services.TryIt = {};
RAML.Security = {};
RAML.Settings = RAML.Settings || {};
// Angular Modules
angular.module('RAML.Directives', []);
angular.module('RAML.Services', ['raml']);
angular.module('RAML.Security', []);
angular.module('ramlConsoleApp', [
'RAML.Directives',
'RAML.Services',
'RAML.Security',
'hc.marked',
'ui.codemirror',
'hljs'
]).config(function (hljsServiceProvider) {
hljsServiceProvider.setOptions({
classPrefix: 'raml-console-hljs-'
});
});
var loc = window.location;
var uri = loc.protocol + '//' + loc.host + loc.pathname.replace(/\/$/, '');
window.hljs.configure({
classPrefix: 'raml-console-hljs-'
});
// Settings
RAML.Settings.proxy = RAML.Settings.proxy || false;
RAML.Settings.oauth2RedirectUri = RAML.Settings.oauth2RedirectUri || uri + '/authentication/oauth2.html';
RAML.Settings.oauth1RedirectUri = RAML.Settings.oauth1RedirectUri || uri + '/authentication/oauth1.html';
RAML.Settings.marked = {
gfm: true,
tables: true,
breaks: true,
pedantic: false,
sanitize: false,
smartLists: true,
silent: false,
langPrefix: 'lang-',
smartypants: false,
headerPrefix: '',
renderer: new window.marked.Renderer(),
xhtml: false,
highlight: function (code, lang) {
var result = [
'<pre class="raml-console-resource-pre raml-console-hljs hljs">',
lang ? window.hljs.highlightAuto(code).value : code,
'</pre>'
];
return result.join('');
}
};
})(window);
(function () {
'use strict';
RAML.Directives.clickOutside = function ($document) {
return {
restrict: 'A',
link: function ($scope, $element, $attrs) {
function onClick (e) {
if ($element[0] === e.target || $element.has(e.target).length) {
return;
}
$scope.$apply($attrs.clickOutside);
}
$document.on('click', onClick);
$scope.$on('$destroy', function () {
$document.off('click', onClick);
});
}
};
};
angular.module('RAML.Directives')
.directive('clickOutside', RAML.Directives.clickOutside);
})();
(function () {
'use strict';
RAML.Directives.closeButton = function() {
return {
restrict: 'E',
templateUrl: 'directives/close-button.tpl.html',
replace: true,
controller: function($scope) {
$scope.close = function () {
var $inactiveElements = jQuery('.raml-console-tab').add('.raml-console-resource').add('li');
$inactiveElements.removeClass('raml-console-is-active');
$scope.showPanel = false;
$scope.traits = null;
$scope.methodInfo = {};
};
}
};
};
angular.module('RAML.Directives')
.directive('closeButton', RAML.Directives.closeButton);
})();
(function () {
'use strict';
RAML.Directives.documentation = function() {
return {
restrict: 'E',
templateUrl: 'directives/documentation.tpl.html',
replace: true,
controller: function($scope) {
var defaultSchemaKey = Object.keys($scope.securitySchemes).sort()[0];
var defaultSchema = $scope.securitySchemes[defaultSchemaKey];
$scope.markedOptions = RAML.Settings.marked;
$scope.documentationSchemeSelected = defaultSchema;
$scope.isSchemeSelected = function isSchemeSelected(scheme) {
return scheme.id === $scope.documentationSchemeSelected.id;
};
$scope.selectDocumentationScheme = function selectDocumentationScheme(scheme) {
$scope.documentationSchemeSelected = scheme;
};
$scope.schemaSettingsDocumentation = function schemaSettingsDocumentation(settings) {
var doc = settings;
if (typeof settings === 'object') {
doc = settings.join(', ');
}
return doc;
};
$scope.unique = function (arr) {
return arr.filter (function (v, i, a) { return a.indexOf (v) === i; });
};
$scope.currentStatusCode = '200';
if ($scope.methodInfo.responseCodes && $scope.methodInfo.responseCodes.length > 0) {
$scope.currentStatusCode = $scope.methodInfo.responseCodes[0];
}
function beautify(body, contentType) {
if(contentType.indexOf('json')) {
body = vkbeautify.json(body, 2);
}
if(contentType.indexOf('xml')) {
body = vkbeautify.xml(body, 2);
}
return body;
}
$scope.getBeatifiedExample = function (value) {
var result = value;
try {
beautify(value, $scope.currentBodySelected);
}
catch (e) { }
return result;
};
$scope.getColorCode = function (code) {
return code[0] + 'xx';
};
$scope.showCodeDetails = function (code) {
$scope.currentStatusCode = code;
};
$scope.isActiveCode = function (code) {
return $scope.currentStatusCode === code;
};
$scope.showRequestDocumentation = true;
$scope.toggleRequestDocumentation = function () {
$scope.showRequestDocumentation = !$scope.showRequestDocumentation;
};
$scope.showResponseDocumentation = true;
$scope.toggleResponseDocumentation = function () {
$scope.showResponseDocumentation = !$scope.showResponseDocumentation;
};
$scope.parameterDocumentation = function (parameter) {
var result = '';
if (parameter) {
if (parameter.required) {
result += 'required, ';
}
if (parameter.enum) {
var enumValues = $scope.unique(parameter.enum);
if (enumValues.length > 1) {
result += 'one of ';
}
result += '(' + enumValues.join(', ') + ')';
} else {
result += parameter.type || '';
}
if (parameter.pattern) {
result += ' matching ' + parameter.pattern;
}
if (parameter.minLength && parameter.maxLength) {
result += ', ' + parameter.minLength + '-' + parameter.maxLength + ' characters';
} else if (parameter.minLength && !parameter.maxLength) {
result += ', at least ' + parameter.minLength + ' characters';
} else if (parameter.maxLength && !parameter.minLength) {
result += ', at most ' + parameter.maxLength + ' characters';
}
if (parameter.minimum && parameter.maximum) {
result += ' between ' + parameter.minimum + '-' + parameter.maximum;
} else if (parameter.minimum && !parameter.maximum) {
result += ' ≥ ' + parameter.minimum;
} else if (parameter.maximum && !parameter.minimum) {
result += ' ≤ ' + parameter.maximum;
}
if (parameter.repeat) {
result += ', repeatable';
}
if (parameter['default']) {
result += ', default: ' + parameter['default'];
}
}
return result;
};
$scope.toggleTab = function ($event) {
var $this = jQuery($event.currentTarget);
var $eachTab = $this.parent().children('.raml-console-toggle-tab');
var $panel = $this.closest('.raml-console-resource-panel');
var $eachContent = $panel.find('.raml-console-resource-panel-content');
if (!$this.hasClass('raml-console-is-active')) {
$eachTab.toggleClass('raml-console-is-active');
$eachContent.toggleClass('raml-console-is-active');
}
};
$scope.changeType = function ($event, type, code) {
var $this = jQuery($event.currentTarget);
var $panel = $this.closest('.raml-console-resource-body-heading');
var $eachContent = $panel.find('span');
$eachContent.removeClass('raml-console-is-active');
$this.addClass('raml-console-is-active');
$scope.responseInfo[code].currentType = type;
};
$scope.changeResourceBodyType = function ($event, type) {
var $this = jQuery($event.currentTarget);
var $panel = $this.closest('.raml-console-request-body-heading');
var $eachContent = $panel.find('span');
$eachContent.removeClass('raml-console-is-active');
$this.addClass('raml-console-is-active');
$scope.currentBodySelected = type;
};
$scope.getBodyId = function (bodyType) {
return jQuery.trim(bodyType.toString().replace(/\W/g, ' ')).replace(/\s+/g, '_');
};
$scope.bodySelected = function (value) {
return value === $scope.currentBodySelected;
};
$scope.$watch('currentBodySelected', function (value) {
var $container = jQuery('.raml-console-request-body-heading');
var $elements = $container.find('span');
$elements.removeClass('raml-console-is-active');
$container.find('.raml-console-body-' + $scope.getBodyId(value)).addClass('raml-console-is-active');
});
$scope.showSchema = function ($event) {
var $this = jQuery($event.currentTarget);
var $panel = $this.closest('.raml-console-schema-container');
var $schema = $panel.find('.raml-console-resource-pre-toggle');
$this.toggleClass('raml-console-is-active');
if (!$schema.hasClass('raml-console-is-active')) {
$this.text('Hide Schema');
$schema
.addClass('raml-console-is-active')
.velocity('slideDown');
} else {
$this.text('Show Schema');
$schema
.removeClass('raml-console-is-active')
.velocity('slideUp');
}
};
}
};
};
angular.module('RAML.Directives')
.directive('documentation', RAML.Directives.documentation);
})();
(function () {
'use strict';
angular.module('RAML.Directives').directive('dynamicName', ['$parse', function($parse) {
return {
restrict: 'A',
controller: function($scope, $element, $attrs){
var name = $parse($attrs.dynamicName)($scope);
delete($attrs.dynamicName);
$element.removeAttr('data-dynamic-name');
$element.removeAttr('dynamic-name');
$attrs.$set('name', name);
}
};
}]);
})();
(function () {
'use strict';
RAML.Directives.methodList = function() {
return {
restrict: 'E',
templateUrl: 'directives/method-list.tpl.html',
replace: true,
controller: function($scope, $location, $anchorScroll, $rootScope) {
function loadExamples () {
$scope.context.uriParameters.reset($scope.resource.uriParametersForDocumentation);
$scope.context.queryParameters.reset($scope.methodInfo.queryParameters);
$scope.context.headers.reset($scope.methodInfo.headers.plain);
if ($scope.context.bodyContent) {
var definitions = $scope.context.bodyContent.definitions;
Object.keys(definitions).map(function (key) {
if (typeof definitions[key].reset !== 'undefined') {
definitions[key].reset($scope.methodInfo.body[key].formParameters);
} else {
definitions[key].value = definitions[key].contentType.example;
}
});
}
}
function getResponseInfo() {
var responseInfo = {};
var responses = $scope.methodInfo.responses;
if (responses) {
Object.keys(responses).map(function (key) {
if(responses[key] && typeof responses[key].body !== 'undefined') {
responseInfo[key] = {};
Object.keys(responses[key].body).sort().reverse().map(function (type) {
responseInfo[key][type] = responses[key].body[type];
responseInfo[key].currentType = type;
});
}
});
}
return responseInfo;
}
function toUIModel (collection) {
if(collection) {
Object.keys(collection).map(function (key) {
collection[key][0].id = key;
});
}
}
function beautifyCustomSecuritySchemeName (name) {
return (name.charAt(0).toUpperCase() + name.slice(1)).replace(/_/g, ' ');
}
$scope.readTraits = function (traits) {
var list = [];
var traitList = traits || [];
traitList = traitList.concat($scope.resource.traits);
traitList.map(function (trait) {
if (trait) {
if (typeof trait === 'object') {
trait = Object.keys(trait).join(', ');
}
if (list.indexOf(trait) === -1) {
list.push(trait);
}
}
});
return list.join(', ');
};
$scope.generateId = function (path) {
return jQuery.trim(path.toString().replace(/\W/g, ' ')).replace(/\s+/g, '_');
};
var $inactiveElements = jQuery('.raml-console-tab').add('.raml-console-resource')
.add('li')
.add('.raml-console-tab');
$scope.$on('openMethod', function(event, $currentScope) {
if ($scope.$id !== $currentScope.$id) {
$inactiveElements.removeClass('raml-console-is-active');
$scope.showPanel = false;
}
});
$scope.showResource = function ($event, $index) {
var $this = jQuery($event.currentTarget);
var $resource = $this.closest('.raml-console-resource');
var methodInfo = $scope.resource.methods[$index];
var $inactiveElements = jQuery('.raml-console-tab').add('.raml-console-resource')
.add('li')
.add('.raml-console-tab');
$scope.methodInfo = methodInfo;
$scope.responseInfo = getResponseInfo();
$scope.context = new RAML.Services.TryIt.Context($scope.raml.baseUriParameters, $scope.resource, $scope.methodInfo);
$scope.requestUrl = '';
$scope.response = {};
$scope.requestOptions = {};
$scope.requestEnd = false;
$scope.showRequestMetadata = false;
$scope.showMoreEnable = true;
$scope.showSpinner = false;
$scope.securitySchemes = $scope.methodInfo.securitySchemes();
$scope.credentials = {};
$scope.traits = $scope.readTraits($scope.methodInfo.is);
$scope.context.customParameters = { headers: [], queryParameters: [] };
$scope.currentBodySelected = methodInfo.body ? Object.keys(methodInfo.body)[0] : 'application/json';
toUIModel($scope.methodInfo.queryParameters);
toUIModel($scope.methodInfo.headers.plain);
toUIModel($scope.resource.uriParametersForDocumentation);
Object.keys($scope.securitySchemes).map(function (key) {
var type = $scope.securitySchemes[key].type;
$scope.securitySchemes[key].name = type;
$scope.securitySchemes[key].id = type + '|' + key;
if (type === 'x-custom') {
$scope.securitySchemes[key].name = beautifyCustomSecuritySchemeName(key);
$scope.securitySchemes[key].id = type + '|' + key;
}
});
$rootScope.$broadcast('resetData');
/*jshint camelcase: false */
// Digest Authentication is not supported
delete $scope.securitySchemes.digest_auth;
/*jshint camelcase: true */
loadExamples();
// Hack for codemirror
setTimeout(function () {
var editors = jQuery('.raml-console-sidebar-content-wrapper #sidebar-body .raml-console-codemirror-body-editor .CodeMirror');
editors.map(function (index) {
var bodyEditor = editors[index].CodeMirror;
if (bodyEditor && $scope.context.bodyContent) {
bodyEditor.setOption('mode', $scope.context.bodyContent.selected);
bodyEditor.refresh();
}
});
}, 10);
if (!$resource.hasClass('raml-console-is-active')) {
var hash = $scope.generateId($scope.resource.pathSegments);
$rootScope.$broadcast('openMethod', $scope);
jQuery($this).addClass('raml-console-is-active');
$scope.showPanel = true;
$location.hash(hash);
$anchorScroll();
} else if (jQuery($this).hasClass('raml-console-is-active')) {
$scope.showPanel = false;
$inactiveElements.removeClass('raml-console-is-active');
$scope.traits = null;
$scope.methodInfo = {};
} else {
jQuery($this).addClass('raml-console-is-active');
jQuery($this).siblings('.raml-console-tab').removeClass('raml-console-is-active');
}
};
}
};
};
angular.module('RAML.Directives')
.directive('methodList', RAML.Directives.methodList);
})();
(function () {
'use strict';
RAML.Directives.namedParameters = function() {
return {
restrict: 'E',
templateUrl: 'directives/named-parameters.tpl.html',
replace: true,
scope: {
src: '=',
context: '=',
type: '@',
title: '@'
},
controller: function ($scope, $attrs) {
$scope.markedOptions = RAML.Settings.marked;
if ($attrs.hasOwnProperty('enableCustomParameters')) {
$scope.enableCustomParameters = true;
}
if ($attrs.hasOwnProperty('showBaseUrl')) {
$scope.showBaseUrl = true;
}
$scope.segments = [];
var baseUri = $scope.$parent.raml.baseUri;
if (typeof baseUri !== 'undefined' && baseUri.templated) {
var tokens = baseUri.tokens;
for (var i = 0; i < tokens.length; i++) {
$scope.segments.push({
name: tokens[i],
templated: typeof baseUri.parameters[tokens[i]] !== 'undefined' ? true : false
});
}
}
$scope.$parent.resource.pathSegments.map(function (element) {
var tokens = element.tokens;
for (var i = 0; i < tokens.length; i++) {
$scope.segments.push({
name: tokens[i],
templated: element.templated && typeof element.parameters[tokens[i]] !== 'undefined' ? true : false
});
}
});
$scope.addCustomParameter = function () {
$scope.context.customParameters[$scope.type].push({});
};
$scope.removeCutomParam = function (param) {
$scope.context.customParameters[$scope.type] = $scope.context.customParameters[$scope.type].filter(function (el) {
return el.name !== param.name;
});
};
}
};
};
angular.module('RAML.Directives')
.directive('namedParameters', RAML.Directives.namedParameters);
})();
(function () {
'use strict';
var generator = window.ramlClientGenerator;
function downloadClient (language, ast) {
var zip = new window.JSZip();
var output = generator[language](ast);
var title = window.slug(output.context.title);
Object.keys(output.files).forEach(function (key) {
zip.file(key, output.files[key]);
});
var content = zip.generate({ type: 'blob' });
var filename = title + '-' + language + '.zip';
// Download as a zip file with an appropriate language name.
window.saveAs(content, filename);
}
RAML.Directives.ramlClientGenerator = function () {
return {
restrict: 'E',
templateUrl: 'directives/raml-client-generator.tpl.html',
controller: function ($scope) {
$scope.downloadJavaScriptClient = function () {
return downloadClient('javascript', $scope.rawRaml);
};
}
};
};
angular.module('RAML.Directives')
.directive('ramlClientGenerator', RAML.Directives.ramlClientGenerator);
})();
(function () {
'use strict';
RAML.Directives.ramlField = function() {
return {
restrict: 'E',
templateUrl: 'directives/raml-field.tpl.html',
replace: true,
scope: {
model: '=',
param: '='
},
controller: function($scope) {
var bodyContent = $scope.$parent.context.bodyContent;
var context = $scope.$parent.context[$scope.$parent.type];
if (bodyContent) {
context = context || bodyContent.definitions[bodyContent.selected];
}
Object.keys(context.plain).map(function (key) {
var definition = context.plain[key].definitions[0];
if (typeof definition.enum !== 'undefined') {
context.values[definition.id][0] = definition.enum[0];
}
});
$scope.canOverride = function (definition) {
return definition.type === 'boolean' || typeof definition.enum !== 'undefined';
};
$scope.overrideField = function ($event, definition) {
var $this = jQuery($event.currentTarget);
var $container = $this.closest('p');
var $el = $container.find('#' + definition.id);
var $checkbox = $container.find('#checkbox_' + definition.id);
var $select = $container.find('#select_' + definition.id);
$el.toggleClass('raml-console-sidebar-override-show');
$checkbox.toggleClass('raml-console-sidebar-override-hide');
$select.toggleClass('raml-console-sidebar-override-hide');
$this.text('Override');
if($el.hasClass('raml-console-sidebar-override-show')) {
definition.overwritten = true;
$this.text('Cancel override');
} else {
definition.overwritten = false;
$scope.context[$scope.type].values[definition.id][0] = definition.enum[0];
}
};
$scope.onChange = function () {
$scope.$parent.context.forceRequest = false;
};
$scope.isDefault = function (definition) {
return typeof definition.enum === 'undefined' && definition.type !== 'boolean';
};
$scope.isEnum = function (definition) {
return typeof definition.enum !== 'undefined';
};
$scope.isBoolean = function (definition) {
return definition.type === 'boolean';
};
$scope.hasExampleValue = function (value) {
return $scope.isEnum(value) ? false : value.type === 'boolean' ? false : typeof value.enum !== 'undefined' ? false : typeof value.example !== 'undefined' ? true : false;
};
$scope.reset = function (param) {
var type = $scope.$parent.type || 'bodyContent';
var info = {};
info[param.id] = [param];
$scope.$parent.context[type].reset(info, param.id);
};
$scope.unique = function (arr) {
return arr.filter (function (v, i, a) { return a.indexOf (v) === i; });
};
}
};
};
angular.module('RAML.Directives')
.directive('ramlField', RAML.Directives.ramlField);
})();
(function () {
'use strict';
RAML.Directives.ramlInitializer = function(ramlParserWrapper) {
return {
restrict: 'E',
templateUrl: 'directives/raml-initializer.tpl.html',
replace: true,
controller: function($scope, $window) {
$scope.ramlUrl = '';
ramlParserWrapper.onParseError(function(error) {
/*jshint camelcase: false */
var context = error.context_mark || error.problem_mark;
/*jshint camelcase: true */
$scope.errorMessage = error.message;
if (context && !$scope.isLoadedFromUrl) {
$scope.raml = context.buffer;
$window.ramlErrors.line = context.line;
$window.ramlErrors.message = error.message;
// Hack to update codemirror
setTimeout(function () {
var editor = jQuery('.raml-console-initializer-input-container .CodeMirror')[0].CodeMirror;
editor.addLineClass(context.line, 'background', 'line-error');
editor.doc.setCursor(context.line);
}, 10);
}
$scope.ramlStatus = null;
$scope.$apply.apply($scope, null);
});
ramlParserWrapper.onParseSuccess(function() {
$scope.ramlStatus = 'loaded';
});
$scope.onChange = function () {
$scope.errorMessage = null;
};
$scope.onKeyPressRamlUrl = function ($event) {
if ($event.keyCode === 13) {
$scope.loadFromUrl();
}
};
$scope.loadFromUrl = function () {
if ($scope.ramlUrl) {
$scope.isLoadedFromUrl = true;
$scope.ramlStatus = 'loading';
ramlParserWrapper.load($scope.ramlUrl);
}
};
$scope.loadRaml = function() {
if ($scope.raml) {
$scope.ramlStatus = 'loading';
$scope.isLoadedFromUrl = false;
ramlParserWrapper.parse($scope.raml);
}
};
if (document.location.search.indexOf('?raml=') !== -1) {
$scope.ramlUrl = document.location.search.replace('?raml=', '');
$scope.loadFromUrl();
}
}
};
};
angular.module('RAML.Directives')
.directive('ramlInitializer', RAML.Directives.ramlInitializer);
})();
(function () {
'use strict';
RAML.Directives.resourcePanel = function() {
return {
restrict: 'E',
templateUrl: 'directives/resource-panel.tpl.html',
replace: true
};
};
angular.module('RAML.Directives')
.directive('resourcePanel', RAML.Directives.resourcePanel);
})();
(function () {
'use strict';
RAML.Directives.rootDocumentation = function() {
return {
restrict: 'E',
templateUrl: 'directives/root-documentation.tpl.html',
replace: true,
controller: function($scope, $location) {
$scope.markedOptions = RAML.Settings.marked;
$scope.selectedSection = 'all';
$scope.hasDocumentationWithIndex = function () {
var regex = /(^#|^##)+\s(.*)$/gim;
return $scope.raml.documentation.filter(function (el) {
return regex.test(el.content);
}).length > 0;
};
$scope.generateDocId = function (path) {
return jQuery.trim(path.toString().replace(/\W/g, ' ')).replace(/\s+/g, '_').toLowerCase();
};
$scope.toggleSection = function ($event, key, section) {
$scope.selectedDocumentSection = key;
$scope.documentationEnabled = !$scope.documentationEnabled;
$location.hash($scope.generateDocId(section));
};
$scope.closeDocumentation = function ($event) {
var $container = jQuery($event.currentTarget).closest('.raml-console-documentation');
$container.toggleClass('raml-console-documentation-active');
$scope.documentationEnabled = false;
};
$scope.sectionChange = function (value) {
$scope.selectedDocumentSection = value;
};
$scope.getDocumentationContent = function (content, selected) {
var lines = content.split('\n');
var index = lines.indexOf(selected);
var result = [];
var regex = /(^#|^##)+\s(.*)$/gim;
result.push(lines[index]);
for (var i = index+1; i < lines.length; i++) {
var line = lines[i];
if (regex.test(line)) {
break;
}
result.push(line);
}
return !selected || selected === 'all' ? content : result.join('\n');
};
$scope.filterHeaders = function (c) {
return c.filter(function (el) {
return el.heading <= 2;
});
};
$scope.getMarkdownHeaders = function (content) {
var headers = content.match(/^#+\s(.*)$/gim);
var result = [];
var regex = new RegExp(/(^#|^##)+\s(.*)$/gim);
if (headers) {
var key = headers[0];
headers.map(function(el) {
if(el.match(regex) !== null) {
key = el;
}
result.push({
value: key,
heading: el.match(/#/g).length,
label: el.replace(/#/ig, '').trim()
});
});
}
return result;
};
}
};
};
angular.module('RAML.Directives')
.directive('rootDocumentation', RAML.Directives.rootDocumentation);
})();
(function () {
'use strict';
RAML.Directives.sidebar = function() {
return {
restrict: 'E',
templateUrl: 'directives/sidebar.tpl.html',
replace: true,
controller: function ($scope, $location, $anchorScroll) {
var defaultSchemaKey = Object.keys($scope.securitySchemes).sort()[0];
var defaultSchema = $scope.securitySchemes[defaultSchemaKey];
$scope.markedOptions = RAML.Settings.marked;
$scope.currentSchemeType = defaultSchema.type;
$scope.currentScheme = defaultSchema.id;
$scope.responseDetails = false;
$scope.currentProtocol = $scope.raml.protocols[0];
function readCustomSchemeInfo (name) {
if (!$scope.methodInfo.headers.plain) {
$scope.methodInfo.headers.plain = {};
}
updateContextData('headers', name, $scope.methodInfo.headers.plain, $scope.context.headers);
updateContextData('queryParameters', name, $scope.methodInfo.queryParameters, $scope.context.queryParameters);
}
if (defaultSchema.type === 'x-custom') {
readCustomSchemeInfo(defaultSchema.id.split('|')[1]);
}
function completeAnimation (element) {
jQuery(element).removeAttr('style');
}
function parseHeaders(headers) {
var parsed = {}, key, val, i;
if (!headers) {
return parsed;
}
headers.split('\n').forEach(function(line) {
i = line.indexOf(':');
key = line.substr(0, i).trim().toLowerCase();
val = line.substr(i + 1).trim();
if (key) {
if (parsed[key]) {
parsed[key] += ', ' + val;
} else {
parsed[key] = val;
}
}
});
return parsed;
}
function apply () {
$scope.$apply.apply($scope, arguments);
}
function beautify(body, contentType) {
if(contentType.indexOf('json')) {
body = vkbeautify.json(body, 2);
}
if(contentType.indexOf('xml')) {
body = vkbeautify.xml(body, 2);
}
return body;
}
function handleResponse(jqXhr, err) {
$scope.response.status = jqXhr ? jqXhr.status : err ? err.status : 0;
if (jqXhr) {
$scope.response.headers = parseHeaders(jqXhr.getAllResponseHeaders());
if ($scope.response.headers['content-type']) {
$scope.response.contentType = $scope.response.headers['content-type'].split(';')[0];
}
$scope.currentStatusCode = jqXhr.status.toString();
try {
$scope.response.body = beautify(jqXhr.responseText, $scope.response.contentType);
}
catch (e) {
$scope.response.body = jqXhr.responseText;
}
}
$scope.requestEnd = true;
$scope.showMoreEnable = true;
$scope.showSpinner = false;
$scope.responseDetails = true;
var hash = 'request_' + $scope.generateId($scope.resource.pathSegments);
$location.hash(hash);
$anchorScroll();
// If the response fails because of CORS, responseText is null
var editorHeight = 50;
if (jqXhr && jqXhr.responseText) {
var lines = $scope.response.body.split('\n').length;
editorHeight = lines > 100 ? 2000 : 25*lines;
}
$scope.editorStyle = {
height: editorHeight + 'px'
};
apply();
}
function resolveSegementContexts(pathSegments, uriParameters) {
var segmentContexts = [];
pathSegments.forEach(function (element) {
if (element.templated) {
var segment = {};
Object.keys(element.parameters).map(function (key) {
segment[key] = uriParameters[key];
});
segmentContexts.push(segment);
} else {
segmentContexts.push({});
}
});
return segmentContexts;
}
function validateForm(form) {
var errors = form.$error;
// var uriParams = $scope.context.uriParameters.plain;
var flag = false;
Object.keys(form.$error).map(function (key) {
for (var i = 0; i < errors[key].length; i++) {
var fieldName = errors[key][i].$name;
// var fieldValue = form[fieldName].$viewValue;
form[fieldName].$setViewValue(form[fieldName].$viewValue);
// Enforce request without URI parameters
// if (typeof uriParams[fieldName] !== 'undefined' && (typeof fieldValue === 'undefined' || fieldValue === '')) {
// flag = true;
// break;
// }
}
});
if (flag) {
$scope.context.forceRequest = false;
}
}
function getParameters (context, type) {
var params = {};
var customParameters = context.customParameters[type];
if (!RAML.Utils.isEmpty(context[type].data())) {
params = context[type].data();
}
if (customParameters.length > 0) {
for(var i = 0; i < customParameters.length; i++) {
var key = customParameters[i].name;
params[key] = [];
params[key].push(customParameters[i].value);
}
}
return params;
}
function clearCustomFields (types) {
types.map(function (type) {
var custom = $scope.context.customParameters[type];
for (var i = 0; i < custom.length; i++) {
custom[i].value = '';
}
});
}
$scope.$on('resetData', function() {
var defaultSchemaKey = Object.keys($scope.securitySchemes).sort()[0];
var defaultSchema = $scope.securitySchemes[defaultSchemaKey];
$scope.currentSchemeType = defaultSchema.type;
$scope.currentScheme = defaultSchema.id;
$scope.currentProtocol = $scope.raml.protocols[0];
$scope.documentationSchemeSelected = defaultSchema;
});
$scope.cancelRequest = function () {
$scope.showSpinner = false;
};
$scope.prefillBody = function (current) {
var definition = $scope.context.bodyContent.definitions[current];
definition.value = definition.contentType.example;
};
$scope.clearFields = function () {
$scope.context.uriParameters.clear($scope.resource.uriParametersForDocumentation);
$scope.context.queryParameters.clear($scope.methodInfo.queryParameters);
$scope.context.headers.clear($scope.methodInfo.headers.plain);
if ($scope.context.bodyContent) {
$scope.context.bodyContent.definitions[$scope.context.bodyContent.selected].value = '';
}
$scope.context.forceRequest = false;
if ($scope.credentials) {
Object.keys($scope.credentials).map(function (key) {
$scope.credentials[key] = '';
});
}
clearCustomFields(['headers', 'queryParameters']);
if ($scope.context.bodyContent) {
var current = $scope.context.bodyContent.selected;
var definition = $scope.context.bodyContent.definitions[current];
if (typeof definition.clear !== 'undefined') {
definition.clear($scope.methodInfo.body[current].formParameters);
} else {
definition.value = '';
}
}
};
$scope.resetFormParameter = function (param) {
var current = $scope.context.bodyContent.selected;
var definition = $scope.context.bodyContent.definitions[current];
definition.reset($scope.methodInfo.body[current].formParameters, param.id);
};
$scope.resetFields = function () {
$scope.context.uriParameters.reset($scope.resource.uriParametersForDocumentation);
$scope.context.queryParameters.reset($scope.methodInfo.queryParameters);
$scope.context.headers.reset($scope.methodInfo.headers.plain);
if ($scope.context.bodyContent) {
var current = $scope.context.bodyContent.selected;
var definition = $scope.context.bodyContent.definitions[current];
if (typeof definition.reset !== 'undefined') {
definition.reset($scope.methodInfo.body[current].formParameters);
} else {
definition.value = definition.contentType.example;
}
}
$scope.context.forceRequest = false;
};
$scope.requestBodySelectionChange = function (bodyType) {
$scope.currentBodySelected = bodyType;
};
$scope.toggleBodyType = function ($event, bodyType) {
var $this = jQuery($event.currentTarget);
var $panel = $this.closest('.raml-console-sidebar-toggle-type').find('button');
$panel.removeClass('raml-console-is-active');
$this.addClass('raml-console-is-active');
$scope.context.bodyContent.selected = bodyType;
};
$scope.getHeaderValue = function (header) {
if (typeof header === 'string') {
return header;
}
return header[0];
};
$scope.hasExampleValue = function (value) {
return typeof value !== 'undefined' ? true : false;
};
$scope.context.forceRequest = false;
function cleanSchemeMetadata(collection, context) {
if (collection) {
Object.keys(collection).map(function (key) {
if (collection[key][0].isFromSecurityScheme) {
delete collection[key];
}
if (context.plain[key].definitions[0].isFromSecurityScheme) {
delete context.plain[key];
}
});
}
}
function updateContextData (type, scheme, collection, context) {
var details = $scope.securitySchemes[scheme].describedBy || {};
var securityHeaders = details[type] || {};
if (securityHeaders) {
Object.keys(securityHeaders).map(function (key) {
if (!securityHeaders[key]) {
securityHeaders[key] = {
id: key,
type: 'string'
};
}
securityHeaders[key].displayName = key;
securityHeaders[key].isFromSecurityScheme = true;
collection[key] = [securityHeaders[key]];
context.plain[key] = {
definitions: [securityHeaders[key]],
selected: securityHeaders[key].type
};
context.values[key] = [undefined];
});
}
}
$scope.protocolChanged = function protocolChanged(protocol) {
$scope.currentProtocol = protocol;
};
$scope.securitySchemeChanged = function securitySchemeChanged(scheme) {
var info = scheme.split('|');
var type = info[0];
var name = info[1];
$scope.currentSchemeType = type;
$scope.context.forceRequest = false;
cleanSchemeMetadata($scope.methodInfo.headers.plain, $scope.context.headers);
cleanSchemeMetadata($scope.methodInfo.queryParameters, $scope.context.queryParameters);
$scope.documentationSchemeSelected = $scope.securitySchemes[name];
if (type === 'x-custom') {
readCustomSchemeInfo(name);
}
};
$scope.tryIt = function ($event) {
$scope.requestOptions = null;
$scope.responseDetails = false;
$scope.response = {};
validateForm($scope.form);
if (!$scope.context.forceRequest) {
jQuery($event.currentTarget).closest('form').find('.ng-invalid').first().focus();
}
if($scope.context.forceRequest || $scope.form.$valid) {
var url;
var context = $scope.context;
var segmentContexts = resolveSegementContexts($scope.resource.pathSegments, $scope.context.uriParameters.data());
$scope.showSpinner = true;
$scope.toggleRequestMetadata($event, true);
try {
var pathBuilder = context.pathBuilder;
var client = RAML.Client.create($scope.raml, function(client) {
if ($scope.raml.baseUriParameters) {
Object.keys($scope.raml.baseUriParameters).map(function (key) {
var uriParameters = $scope.context.uriParameters.data();
pathBuilder.baseUriContext[key] = uriParameters[key][0];
delete uriParameters[key];
});
}
client.baseUriParameters(pathBuilder.baseUriContext);
});
client.baseUri = client.baseUri.replace(/(https)|(http)/, $scope.currentProtocol.toLocaleLowerCase());
url = client.baseUri + pathBuilder(segmentContexts);
} catch (e) {
$scope.response = {};
return;
}
var request = RAML.Client.Request.create(url, $scope.methodInfo.method);
$scope.parameters = getParameters(context, 'queryParameters');
request.queryParams($scope.parameters);
request.headers(getParameters(context, 'headers'));
if (context.bodyContent) {
request.header('Content-Type', context.bodyContent.selected);
request.data(context.bodyContent.data());
}
var authStrategy;
try {
var securitySchemes = $scope.methodInfo.securitySchemes();
var scheme;
Object.keys(securitySchemes).map(function(key) {
if (securitySchemes[key].type === $scope.currentSchemeType) {
scheme = securitySchemes && securitySchemes[key];
return;
}
});
//// TODO: Make a uniform interface
if (scheme && scheme.type === 'OAuth 2.0') {
authStrategy = new RAML.Client.AuthStrategies.Oauth2(scheme, $scope.credentials);
authStrategy.authenticate(request.toOptions(), function (jqXhr, err) {
$scope.requestOptions = request.toOptions();
handleResponse(jqXhr, err);
});
return;
}
authStrategy = RAML.Client.AuthStrategies.for(scheme, $scope.credentials);
authStrategy.authenticate().then(function(token) {
token.sign(request);
$scope.requestOptions = request.toOptions();
jQuery.ajax(request.toOptions()).then(
function(data, textStatus, jqXhr) { handleResponse(jqXhr); },
function(jqXhr) { handleResponse(jqXhr); }
);
});
$scope.requestOptions = request.toOptions();
} catch (e) {
// custom strategies aren't supported yet.
}
} else {
$scope.context.forceRequest = true;
}
};
$scope.documentationEnabled = true;
$scope.toggleSidebar = function ($event) {
var $this = jQuery($event.currentTarget);
var $panel = $this.closest('.raml-console-resource-panel');
var $sidebar = $panel.find('.raml-console-sidebar');
var sidebarWidth = 0;
if (jQuery(window).width() > 960) {
sidebarWidth = 430;
}
if ($sidebar.hasClass('raml-console-is-fullscreen')) {
$scope.documentationEnabled = true;
$sidebar.velocity(
{ width: $scope.singleView ? 0 : sidebarWidth },
{
duration: 200,
complete: function (element) {
jQuery(element).removeAttr('style');
$sidebar.removeClass('raml-console-is-fullscreen');
}
}
);
$sidebar.removeClass('raml-console-is-responsive');
$panel.removeClass('raml-console-has-sidebar-fullscreen');
} else {
$sidebar.velocity(
{ width: '100%' },
{
duration: 200,
complete: function (element) {
jQuery(element).removeAttr('style');
$scope.documentationEnabled = false;
apply();
}
}
);
$sidebar.addClass('raml-console-is-fullscreen');
$sidebar.addClass('raml-console-is-responsive');
$panel.addClass('raml-console-has-sidebar-fullscreen');
}
if ($scope.singleView) {
$sidebar.toggleClass('raml-console-is-collapsed');
$panel.toggleClass('raml-console-has-sidebar-collapsed');
}
};
$scope.collapseSidebar = function ($event) {
var $this = jQuery($event.currentTarget);
var $panel = $this.closest('.raml-console-resource-panel');
var $panelContent = $panel.find('.raml-console-resource-panel-primary');
var $sidebar = $panel.find('.raml-console-sidebar');
var animation = 430;
var speed = 200;
if ((!$sidebar.hasClass('raml-console-is-fullscreen') && !$sidebar.hasClass('raml-console-is-collapsed')) || $sidebar.hasClass('raml-console-is-responsive')) {
animation = 0;
}
if ($scope.singleView) {
$panel.toggleClass('raml-console-has-sidebar-fullscreen');
speed = 0;
}
$sidebar.velocity(
{ width: animation },
{
duration: speed,
complete: function (element) {
jQuery(element).removeAttr('style');
if ($scope.singleView) {
$scope.documentationEnabled = false;
}
apply();
}
}
);
$panelContent.velocity(
{ 'padding-right': animation },
{
duration: speed,
complete: completeAnimation
}
);
$sidebar.toggleClass('raml-console-is-collapsed');
$sidebar.removeClass('raml-console-is-responsive');
$panel.toggleClass('raml-console-has-sidebar-collapsed');
if ($sidebar.hasClass('raml-console-is-fullscreen') || $scope.singleView) {
$sidebar.toggleClass('raml-console-is-fullscreen');
}
};
$scope.toggleRequestMetadata = function (enabled) {
if ($scope.showRequestMetadata && !enabled) {
$scope.showRequestMetadata = false;
} else {
$scope.showRequestMetadata = true;
}
};
$scope.showResponseMetadata = true;
$scope.toggleResponseMetadata = function () {
$scope.showResponseMetadata = !$scope.showResponseMetadata;
};
}
};
};
angular.module('RAML.Directives')
.directive('sidebar', RAML.Directives.sidebar);
})();
(function () {
'use strict';
RAML.Directives.spinner = function() {
return {
restrict: 'E',
templateUrl: 'directives/spinner.tpl.html',
replace: true,
link: function($scope, $element) {
$scope.$on('loading-started', function() {
$element.css({ 'display': ''});
});
$scope.$on('loading-complete', function() {
$element.css({ 'display': 'none' });
});
}
};
};
angular.module('RAML.Directives')
.directive('spinner', RAML.Directives.spinner);
})();
(function () {
'use strict';
RAML.Directives.theme = function() {
return {
restrict: 'E',
templateUrl: 'directives/theme-switcher.tpl.html',
replace: true,
link: function