Access parameter of Node.js module function - javascript

im totally new to node.js and i couldn't find a similar question for my problem. I'm sure it's easy to solve for one of u guys... at least i guess.
I'm trying to get a special paragraph of a wikipage using the npm mediawiki module for node.js! I get the paragraph using the pre-defined function as following:
bot.page(title).complete(function (title, text, date) {
//extract section '== Check ==' from wikipage&clean string
var result = S(text).between('== Check ==', '==').s;
});
Thats working. What i want is: to use "result" outside of that code block in other functions. I think it has something to do with callbacks but im not sure how to handle it as this is a pre-defined function from the mediawiki module.
The example function of the module to get a wikipage looks as following:
/**
* Request the content of page by title
* #param title the title of the page
* #param isPriority (optional) should the request be added to the top of the request queue (defualt: false)
*/
Bot.prototype.page = function (title, isPriority) {
return _page.call(this, { titles: title }, isPriority);
};
which uses the following function of the module:
function _page(query, isPriority) {
var promise = new Promise();
query.action = "query";
query.prop = "revisions";
query.rvprop = "timestamp|content";
this.get(query, isPriority).complete(function (data) {
var pages = Object.getOwnPropertyNames(data.query.pages);
var _this = this;
pages.forEach(function (id) {
var page = data.query.pages[id];
promise._onComplete.call(_this, page.title, page.revisions[0]["*"], new Date(page.revisions[0].timestamp));
});
}).error(function (err) {
promise._onError.call(this, err);
});
return promise;
}
There's also a complete callback function and i dont know how to use it:
/**
* Sets the complete callback
* #param callback a Function to call on complete
*/
Promise.prototype.complete = function(callback){
this._onComplete = callback;
return this;
};
How can i access the "result" variable by using callbacks outside the function of the module? I don't know how to handle the callback as it is a pre-defined function of a module...

What i want is: to use "result" outside of that code block in other functions.
You can't. You need to use the result inside that code block (that code block is called a callback function btw.). You can still pass them to other functions, you just need to do it inside that callback function:
bot.page(title).complete(function (title, text, date) {
//extract section '== Check ==' from wikipage&clean string
var result = S(text).between('== Check ==', '==').s;
other_function(result); // <------------- this is how you use it
});

Related

Protractor passing variable between describe functions

I am trying to pass a variable representing an array between describe functions and I am having no luck. I have used protractor before but never passing variables between describes before. any help would be appreciated.
I combed through the stack over flow pages and could not find a solution.
I even tried to put each describe into a function but protractor said specs not found.
describe('WFN Admin Login Test', function() {
var EC = protractor.ExpectedConditions;
it('Load WFN home page - completed', function() {
browser.get('https://wfn-iat.adp.com/public/index.htm');
expect(browser.getCurrentUrl()).toEqual('https://wfn-iat.adp.com/public/index.htm');
});
var fs = require("fs");
var text = fs.readFileSync("/Users/hoflerj/Desktop/Protractor/clients/clientids.txt").toString('utf-8');
var file = text.split("\n");
console.log(file);
var arrayClient = file;
arrayClient.forEach(function(client){
//call other describe function to pass client variable below
});
});
describe('Get_CycleStatus', function() {
var EC = protractor.ExpectedConditions;
it('Enter Client-ID ', function () {
var search1 = ($$('input[id="toolbarQuickSearch"]').get(0));
browser.wait(EC.elementToBeClickable(search1),20,000).then(function() {
search1.clear().sendKeys('midrfrate'); //----client array variable here
search1.sendKeys(protractor.Key.BACK_SPACE);
browser.sleep(2000);
});
var dropdown = element(by.linkText("midrfrate"));//----client array variable
dropdown.click();
browser.sleep(2000);
});
I will eventually do a loop so that I can input the next client name any help how to do this with protractor would be most helpful. Also after setting up this global variable how would i use a loop to send this to another describe statement?
In your describe call the desired params with browser.params.paramName (in your case browser.params.arrayClient)
For your loop use an array or an object like so:
params: {
array:[ {
glob:'arrauClient',
glob2:'blabla'
}]
then call it in your describe with browser.params.glo

How to test node data chunking function

I'm working on a project which uses node and we're trying to achieve 100% coverage of our functions. This is the only function we haven't tested, and it's within another function.
var userInput = "";
req.on("data", function(data){
userInput += data;
});
How do you go about testing this function? We tried exporting the function from another file but no luck.
I should mention that we are using tape as a testing module.
You need to trigger this "data" event on req. So that this callback will be called.
For instance, let's suppose you have req on your test, you could do something like that (this is Mocha):
req.trigger('data', 'sampleData');
expect(userInput).to.equal('sampleData');
req.emit('data', {sampleData: 'wrongOrRightSampleDataHere'}) should do it.
When instantiating the http or hence the req object make sure you instantiate a new one, that no other test receives this event.
To be more complete...
var assert = require('assert')
function test() {
var hasBeenCalledAtLeastOnce = false
var userInput = "";
// req must be defined somewhere though
req.on("data", function(data){
userInput += data;
if(hasBeenCalledAtLeastOnce) {
assert.equal(userInput, "HelloWorld", "userInput is in fact 'HelloWorld'")
}
hasBeenCalledAtLeastOnce = true
});
req.emit('data', "Hello")
req.emit('data', "World")
}
test()

AngularJS and Restangular, trying to convert update method to API

I'm trying to convert my basic crud operations into an API that multiple components of my application can use.
I have successfully converted all methods, except the update one because it calls for each property on the object to be declared before the put request can be executed.
controller
$scope.update = function(testimonial, id) {
var data = {
name: testimonial.name,
message: testimonial.message
};
dataService.update(uri, data, $scope.id).then(function(response) {
console.log('Successfully updated!');
},
function(error) {
console.log('Error updating.');
});
}
dataService
dataService.update = function(uri, data, id) {
var rest = Restangular.one(uri, id);
angular.forEach(data, function(value, key) {
// needs to be in the format below
// rest.key = data.key
});
// needs to output something like this, depending on what the data is passed
// rest.name = data.name;
// rest.message = data.message;
return rest.put();
}
I tried to describe the problem in the codes comments, but to reiterate I cannot figure out how to generate something like rest.name = data.name; without specifying the name property because the update function shouldn't need to know the object properties.
Here is what the update method looked like before I started trying to make it usable by any of my components (this works)
Testimonial.update = function(testimonial, id) {
var rest = Restangular.one('testimonials', id);
rest.name = testimonial.name;
rest.message = testimonial.message;
return rest.put();
}
How can I recreate this without any specific properties parameters hard-coded in?
Also, my project has included lo-dash, if that helps, I don't know where to start with this problem. Thanks a ton for any advice!
Try like
angular.extend(rest,testimonial)
https://docs.angularjs.org/api/ng/function/angular.extend

Return generated Typekit id in Yeoman Generator

I'm using node-typekit to create a new Typekit empty font set in my Yeoman generator for use in my project. I am able to successfully create the kit, but cannot figure out how to return the kit id value back to the Yeoman generator so I can add the necessary Typekit script tag values to my web pages. Here is the part of my index.js generator script in question:
At the top of index.js:
var kit = require('typekit');
var typekitID = '';
function setTypekitID(theid) {
typekitID = theid;
};
And the app section:
app: function () {
var token = 'xxxxxxxxxxxxxxxxxxxxxxxx';
var split = this.domainname.split('.');
split.pop();
var localdomain = split.join('.') + '.dev';
kit.create(token, {
name: this.appname,
badge: false,
domains: [this.domainname, localdomain],
families: []
}, function (err, data) {
setTypekitID(data.kit.id);
});
}
If instead of:
setTypekitID(data.kit.id);
I use:
console.log(data.kit.id);
The correct kit ID is displayed in the console. However, I can't quite figure out how to pass the data.kit.id value in the callback back to the generator for further use. Given the current code above, it comes back as "undefined".
Any ideas? Thanks!
Without any experience with typekit, I would guess that kit.create is an asynchronous call. When you make such a call, the generator needs to know about it, so it can delay invocation of further methods until it knows your asynchronous callback has had a chance to execute.
Try doing this:
app: function () {
var done = this.async(); // this tells the generator, "hang on, yo."
// ...
kit.create(token, { /* ... */ }, function (err, data) {
setTypekitID(data.kit.id);
done(); // calling this resumes the generator.
});
}
An example of how the default generator-generator uses this can be found here.

WinJS: Loading data

I'm trying to develop my first Windows 8 Store app (HTML/JS). I am using the Grid App Template which suites my Needs I think the best.
This is my model:
I have three entities: 1. GalleryCategory 2. Gallery 3. GalleryItem.
A Gallery is linked to exactly one Category. A GalleryItem is linked to exactly one Gallery...so nothing fancy here...
I'm using the out of the box data.js file to load all categories and all galleries on the Startup of the app. But when I open the galleryDetail.html (which is supposed to Show all the Images of the particular Gallery) I want to load all Images of the Gallery then. (to avoid to much loading on the beginning).
And now I'm finally coming to the Point that I do not understand:
How can I manage this?? I mean
WinJS.UI.Pages.define("/pages/galleryDetail/galleryDetail.html", {
// This function is called whenever a user navigates to this page. It
// populates the page elements with the app's data.
ready: function (element, options) {
var item = options && options.item ? Data.resolveItemReference(options.item) : Data.items.getAt(0);
element.querySelector(".titlearea .pagetitle").textContent = item.group.title;
element.querySelector("article .item-title").textContent = item.title;
element.querySelector("article .item-subtitle").textContent = item.subtitle;
element.querySelector("article .item-image").src = item.backgroundImage;
element.querySelector("article .item-image").alt = item.subtitle;
element.querySelector("article .item-content").innerHTML = item.content;
element.querySelector(".content").focus();
var galleryId = item.key;
WinJS.xhr({ url: "http://someUrlToAnAspNetWebsite/Handlers/GalleryItemsHandler.ashx?galleryId=" + galleryId }).done(
// Complete function
function (response) {
var items = JSON.parse(response.responseText);
items.forEach(function (item) {
galleryItemsList.push(item);
});
dataList = new WinJS.Binding.List(galleryItemsList);
var galleryItemsListView = document.getElementById('galleryItemsListView').winControl;
galleryItemsList.itemDataSource = dataList.dataSource;
},
// Error function
function (response) {
// handle error here...
},
// Progress function
function (response) {
// progress implementation goes here...
}
);
},
my Problem is obivous...the ready function continues / Ends before the data is retrieved...as the async call takes a while.
But I thought using the promise (.done()) will do this for me (synchronising the threads)?? Or do I need to use the join() function. If so, where and how?? Sorry for my issues with this...
Thanks for any help...
The ready function itself is an async function, so you only have to return a promise to tell its caller that its not done until some promise is resolved. So you can fix your issue with 7 key strokes. Just add return before the WinJS.xhr call.

Categories

Resources