Swagger-ui + oauth -> index.js:24 Uncaught TypeError: Cannot read property 'api' of undefined - javascript

first of all i am using a bit modified version of the standard html/js code offered from swagger-ui.
Changes are rather simple, instead of using only a single SwaggerUI element like:
window.swaggerUi = new SwaggerUi({
....
window.swaggerUi.load();
we iterate over them and create lots of swaggerUI elements:
function addSwaggerUI(url, dom_id, host){
window[dom_id] = new SwaggerUi({
....
window[domId].load();
this is our iteration:
var services = [{SERVICE_SPECS}];
var doc_container = document.getElementById('service-doc-container');
var index = 0;
services.forEach(function(serviceSpec) {
var swaggerNode = document.createElement('div');
swaggerNode.id = "swagger-ui-container-" + index;
swaggerNode.className = "swagger-ui-wrap";
var messageNode = document.createElement('div');
messageNode.id = "message-bar-" + index;
messageNode.className = "swagger-ui-wrap";
doc_container.appendChild(swaggerNode);
doc_container.appendChild(messageNode);
log("adding service documentation for " + serviceSpec);
addServiceDocumentation(serviceSpec, swaggerNode.id, "{SERVICE_HOST}");
index++;
});
This worked quiet well until we started using securityDefinitions oAuth:
"securityDefinitions": {
"OauthSecurity": {
"type": "oauth2",
"authorizationUrl": "http://localhost/oauth/dialog",
"flow": "implicit",
"scopes":{
"write:sessions":"kill sessions",
"read:sessions":"get sessions"
}
}
Now i get on each swaggerUI this error:
index.js:24 Uncaught TypeError: Cannot read property 'api' of undefined
Original swaggercode:https://github.com/swagger-api/swagger-ui/tree/master/dist see index.html
Can someone help to fix this?
(Alternative solution: Anyone know of another way to add multiple web apis from different json files on one html page? )
UPDATE:
So i looked at the generated page from swagger.petstore.io and found something called 'authorzie-wrapper'it is possible that this element is missing at my code.

Related

Google Drive REST API v2 file properties array in Google Apps Script is undefined?

I am working to manage some Google Drive files with Google Apps Script. One piece of this project is reviewing properties on files, so I am using the Drive API rather than DriveApp. Additionally, Google Apps Script currently has access to the Drive REST API v2 instead of v3.
I've successfully set a property (id) and am able to pull the files with the property set.
console = Logger;
function Files (folderId) {
var optionalArgs,response
;
optionalArgs = {
q:'"'+folderId+'" in parents',
spaces:"drive"
}
do {
response = Drive.Files.list(optionalArgs);
response.items.forEach(function (file) {
console.log(file.properties);
var id = file.properties.find(function (property) {
return property.key === 'id';
});
this[id.value] = file;
},this);
} while (optionalArgs.pageToken = response.nextPageToken);
}
When running this function, I am able to see the file properties in the log
[{visibility=PUBLIC, kind=drive#property, etag="3GjDSTzy841RsmcBo4Ir-DLlp20/HGzJl78t8I2IehiAlaGXTkm2-C4", value=9e18766b-1cc9-4c1b-8003-b241f43db304, key=id}]
but get
TypeError :Cannot call method "find" of undefined.
I am unable to iterate through this resulting array. Using JSON.parse on it trys to convert it to an object, which is problematic for files with multiple properties. Using JSON.parse(JSON.stringify()) on it results in
SyntaxError: Unexpected token: u
which I understand is resulting from the value being undefined. I could work with that, if my log wasn't telling me otherwise.
"nextPageToken(string) The page token for the next page of files. This will be absent if the end of the files list has been reached."
Quote from: https://developers.google.com/drive/v2/reference/files/list#examples
so this line assigns an undefined value to optionalArgs.pageToken
while (optionalArgs.pageToken = response.nextPageToken);
and does not terminate the loop. A better way is to assign the value of optionalArgs.pageToken inside the loop and break the loop if its value is undefined like this:
console = Logger;
function Files (folderId) {
var optionalArgs,response
;
optionalArgs = {
q:'"'+folderId+'" in parents',
spaces:"drive"
}
do {
response = Drive.Files.list(optionalArgs);
response.items.forEach(function (file) {
console.log(file.properties);
var id = file.properties.find(function (property) {
return property.key === 'id';
});
this[id.value] = file;
},this);
// Assign the value inside the loop
optionalArgs.pageToken = response.nextPageToken
} while (optionalArgs.pageToken != undefined) // check to see if it undefined here and break the loop.
}
You can use v3 in Google Apps Script by selecting the version in the Advance Google Service option:
Just note that you have to follow how to request in Google Drive v3 but you can still use v2 because all of the example is still in v2.
Regarding your error, using their code in the sample code for Listing folders.
function listRootFolders() {
var query = '"root" in parents and trashed = false and ' +
'mimeType = "application/vnd.google-apps.folder"';
var folders, pageToken;
do {
folders = Drive.Files.list({
q: query,
maxResults: 100,
pageToken: pageToken
});
if (folders.items && folders.items.length > 0) {
for (var i = 0; i < folders.items.length; i++) {
var folder = folders.items[i];
Logger.log('%s (ID: %s)', folder.title, folder.id);
}
} else {
Logger.log('No folders found.');
}
pageToken = folders.nextPageToken;
} while (pageToken);
}
You can also read more code implementation of the above documentation.
Hope this helps.

Error Start workflow via JavaScript

I can't get start a Workflow via Web Script.
I created the file workflow.get.js:
var nodeId = args.nodeid; //fdadc86f-d996-472d-8267-850a63573b02
var workflowName = args.w; //jbpm$wf:adhoc
var document = search.findNode("workspace://SpacesStore/" + nodeId);
var workflowAction = actions.create("start-workflow");
workflowAction.parameters.workflowName = workflowName;
workflowAction.parameters["bpm:workflowDescription"] = "Please edit: " + document.name;
workflowAction.parameters["bpm:assignees"] = [people.getPerson("admin"), people.getPerson("admin")];
var futureDate = new Date();
futureDate.setDate(futureDate.getDate() + 7);
workflowAction.parameters["bpm:workflowDueDate"] = futureDate;
workflowAction.execute(document);
workflow.get.desc.xml
<webscript>
<shortname>Start Workflow</shortname>
<description>Testando Start Workflow</description>
<url>/workflow?nodeid={idfile}&&w={namewf}</url>
<format default="html">argument</format>
<authentication>admin</authentication>
<transaction>required</transaction>
</webscript>
and workflow.get.html.ftl
The ${args.w} started!
when I click http://localhost:8080/alfresco/service/workflow?nodeId=fdadc86f-d996-472d-8267-850a63573b02&w=jbpm$wf:adhoc return the error
06190076 Wrapped Exception (with status template): 06190474 Failed to execute script '/triggerworkflow.get.js (in repository store workspace://SpacesStore/Company Home/Data Dictionary/Web Scripts)': 06190473 Can't find method org.alfresco.repo.jscript.ScriptAction.execute(org.mozilla.javascript.Undefined). (in repository store workspace://SpacesStore/Company Home/Data Dictionary/Web Scripts)#11)
Exception: org.alfresco.error.AlfrescoRuntimeException - 08200041 TypeError: Cannot read property "name" from null
(workspace://SpacesStore/Company Home/Data Dictionary/Web Scripts Extensions/Workflow/workflow.get.js#7)
org.alfresco.repo.jscript.RhinoScriptProcessor.executeScriptImpl(RhinoScriptProcessor.java:469)
Exception: org.alfresco.scripts.ScriptException - 08200042 Failed to execute script '/Workflow/workflow.get.js
(in repository store workspace://SpacesStore/Company Home/Data Dictionary/Web Scripts Extensions)': 08200041 TypeError: Cannot read
property "name" from null (workspace://SpacesStore/Company Home/Data Dictionary/Web Scripts Extensions/Workflow/workflow.get.js#7)
org.alfresco.repo.jscript.RhinoScriptProcessor.execute(RhinoScriptProcessor.java:183)
Exception: org.springframework.extensions.webscripts.WebScriptException - 08200035 Wrapped Exception (with status template):
08200042 Failed to execute script '/Workflow/workflow.get.js (in repository store workspace://SpacesStore/Company Home/Data Dictionary/Web Scripts Extensions)'
: 08200041 TypeError: Cannot read property "name" from null (workspace://SpacesStore/Company Home/Data Dictionary/Web Scripts Extensions/Workflow/
workflow.get.js#7)
org.springframework.extensions.webscripts.AbstractWebScript.createStatusException(AbstractWebScript.java:742)
Anybody help me?
Your problem is you're calling arguments one thing in one place, and a different thing in another:
var nodeId = args.nodeid; //fdadc86f-d996-472d-8267-850a63573b02
var workflowName = args.w; //jbpm$wf:adhoc
vs
<url>/workflow?nodeid={idfile}&&w={namewf}</url>
You need to get those to agree! I'd suggest, given the URL you seem to already be using from the client, changing your webscript descriptor URL to match what you use, to:
<url>/workflow?nodeid={nodeid}&w={w}</url>
You should also add logic to check that the node given really exists - search.findNode can return null so you should check that before continuing (eg and give a 404 if not found)
Also, you could use utils.getNodeFromString(String) if you'd rather
Please try to start your workflow using this code,
replace your code of workflow.get.js with this code and change all the properties according to your requirement.
function startWorkflow()
{
var workflowAction = workflow.getDefinitionByName("activiti$test_wf");
var package= workflow.createPackage();
var wfparams = new Array();
wfparams["model_prefix:req_props_name"] = value2;
wfparams["bpm:assignee"] = people.getPerson("ADMIN");
workflowAction.startWorkflow(package, wfparams);
}
}
startWorkflow();

Creating a Parse Role Hierarchy fails with 'parent is undefined'

I get a strange error when setting up a role hierarchy in Parse:
Uncaught ReferenceError: parent is not defined
The roles are all created ok in Parse, and the relation objects I get from getRoles look ok, but when calling the add method I get this error. Anyone else experiencing something similar?
Here's the code (running parse#1.6.3, the parse/node implementation):
function createRolesForOrganization(organization){
var self = Parse.User.current();
var ownerRole = new Parse.Role(organization.id + '_Owner', new Parse.ACL(self)),
adminRole = new Parse.Role(organization.id + '_Admin', new Parse.ACL(self)),
userRole = new Parse.Role(organization.id + '_User', new Parse.ACL(self));
return Parse.Object
.saveAll([
ownerRole,
adminRole,
userRole
])
.then(function(objs){
ownerRole = objs[0];
adminRole = objs[1];
userRole = objs[2];
userRole.getRoles().add(adminRole);
adminRole.getRoles().add(ownerRole);
return Parse.Object.saveAll([
ownerRole,
adminRole,
userRole
]);
});
}
This is a bug in the Parse JavaScript SDK that is reported here:
https://developers.facebook.com/bugs/1677477152487599/
A quick fix in the meantime is to replace 'parent' with 'this.parent' on line 101 in ParseRelation.js, or roll back to a version before 1.6.

How to save a GET response to a variable on ExpressJS and LocomotiveJS

I'm relatively new to NodeJS. I've created an app using ExpressJS and LocomotiveJS framework. How would I save a certain GET response to a variable within a controller.
For example:
file: cartController.js
var locomotive = require('locomotive');
var Controller = locomotive.Controller;
var cartController = new Controller();
var Cart = require('../models/cartsModel.js');
var cart = new Cart();
cartController.index = function(){
var getStoreDetails = function(cart, callback) {
for (var key in cart.productsByStores) {
//*****************************
//This is what I'm looking for:
//*****************************
store_details = this.get('/stores/' . key);
cart.productsByStores[key] = {'store_details' : store_details, 'products' : cart.productsByStores[key]};
}
return this.res.json(cart.productsByStores);
//console.log('store: ', store);
};
}
The response in that GET is already set up. What I'm missing is how to access and save that response to an object.
I've looked over the Locomotive and Express docs and couldn't pull it together.
Any help is appreciated!
Thanks
A little late, but what you're looking for is this.param('stores').
This would also work: this.req.body.stores.

javascript undefined error, but alert toSource shows the object exists

I grabbed a bit of code to do some paging with jQuery, via Luca Matteis here
Paging Through Records Using jQuery
I've made some edits to the paging script so that I can use the same code to provide paging of different content in different locations on the same site.
For the most part, I think it works, except that I get a jsonObj is undefined error in firebug.
When I use alert(jsonObj.toSource()), I am shown the variables that I am trying to populate, but at the same time, the script dies because of the error.
I can't figure out why I am getting this conflict of 'undefined' and yet I can easily out put the 'undefined' values in an alert. I can even say alert(jsonObj.name), and it will give me that value, but still launch an jsonObj is undefined error.
Here's the code I'm using
var pagedContent = {
data: null
,holder: null
,currentIndex : 0
,init: function(data, holder) {
this.data = data;
this.holder=holder;
this.show(0); // show last
}
,show: function(index) {
var jsonObj = this.data[index];
if(!jsonObj) {
return;
}
var holdSubset='';
for(i=0;i<=4; i++){
jsonObj=this.data[index+i];
this.currentIndex = index;
if(this.holder=='div#firstList'){
var returnedId = jsonObj.id;
var returnedName = jsonObj.name;
var calcScore=this.data[index+i].score/this.data[0].score*100;
var resultInput="<div ' id='"+returnedId+"'><div class='name'>"+returnedName+"</div><div class='score'><div style='width:"+calcScore+"%;'></div></div>";
}
if(this.holder=='div#secondList'){
var name=jsonObj.name;
var city=jsonObj.city;
var region=jsonObj.state;
var resultInput='<li><div>'+name+'</div<div>'+city+'</div><div>'+region+'</div></li>';
}
holdSubset= holdSubset+resultInput;
}
jQuery(this.holder).html('<br/>'+holdSubset);
if(index!=0){
var previous = jQuery("<a>").attr("href","#").click(this.previousHandler).text("< previous");
jQuery(this.holder).append(previous);
}
if(index+i<this.data.length){
var next = jQuery("<a style='float:right;'>").attr("href","#").click(this.nextHandler).text("next >");
jQuery(this.holder).append(next);
}
}
,nextHandler: function() {
pagedContent.show(pagedContent.currentIndex + 5);
return false;
}
,previousHandler: function() {
pagedContent.show(pagedContent.currentIndex - 5);
return false
}
};
I call the function like this
pagedContent.init(json.users.locations, 'div#secondList');
The json looks like this
{"locations" : [ {"id":"21319","name":"Naugatuck American Legion","city":"Ansonia","region":"Connecticut"},{"id":"26614","name":"Studio B789","city":"Acton","region":"Maine"},{"id":"26674","name":"Deering Grange Hall","city":"Bailey Island","region":"Maine"},{"id":"27554","name":"Accu Billiards","city":"Acushnet","region":"Massachusetts"}]}
I may have found the problem with your code:
for(i=0;i<=4; i++){
jsonObj=this.data[index+i];
(...)
When you call show(0) you set index to 0. You expect a fixed number of items in the array (5 in the range [0..4]) but there are only 4 locations in your data.
If you are using console.log to trace the problems in firebug you might find that it is a problem with firebug. Try just running console.log on it's own.
If it is a problem with firebug try updating it. There are some development versions around which might fix the problem.
I had a similar problem and fixed it by doing the above.

Categories