How can I leverage reactive extensions to do caching, without a subject? - reactive-programming

I want to be able to fetch data from an external Api for a specific request, but when that data is returned, also make it available in the cache, to represent the current state of the application.
This solution seems to work:
var Rx = require('rx');
var cached_todos = new Rx.ReplaySubject(1);
var api = {
refresh_and_get_todos: function() {
var fetch_todos = Rx.Observable.fromCallback($.get('example.com/todos'));
return fetch_todos()
.tap(todos => cached_todos.onNext(todos));
},
current_todos: function() {
return cached_todos;
}
};
But - apparently Subjects are bad practice in Rx, since they don't really follow functional reactive programming.
What is the right way to do this in a functional reactive programming way?

It is recommended not to use Subjects because there is a tendency to abuse them to inject side-effects as you have done. They are perfectly valid to use as ways of pushing values into a stream, however their scope should be tightly constrained to avoid bleeding state into other areas of code.
Here is the first refactoring, notice that you can create the source beforehand and then your api code is just wrapping it up in a neat little bow:
var api = (function() {
var fetch_todos = Rx.Observable.fromCallback($.get('example.com/todos'))
source = new Rx.Subject(),
cached_todos = source
.flatMapLatest(function() {
return fetch_todos();
})
.replay(null, 1)
.refCount();
return {
refresh: function() {
source.onNext(null);
},
current_todos: function() {
return cached_todos;
}
};
})();
The above is alright, it maintains your current interface and side-effects and state have been contained, but we can do better than that. We can create either an extension method or a static method that accepts an Observable. We can then simplify even further to something along the lines of:
//Executes the function and caches the last result every time source emits
Rx.Observable.withCache = function(fn, count) {
return this.flatMapLatest(function() {
return fn();
})
.replay(null, count || 1)
.refCount();
};
//Later we would use it like so:
var todos = Rx.Observable.fromEvent(/*Button click or whatever*/))
.withCache(
Rx.Observable.fromCallback($.get('example.com/todos')),
1 /*Cache size*/);
todos.subscribe(/*Update state*/);

Related

How to call script include from the client script service-now without GlideAjax

The common process we follow today to get the data on client script:
OnChange client script:
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
var user = g_form.getValue('u_user');
//Call script include
var ga = new GlideAjax('global.sampleUtils'); //Scriptinclude
ga.addParam('sysparm_name', 'getUserDetails'); //Method
ga.addParam('userId',user); //Parameters
ga.getXMLAnswer(getResponse);
function getResponse(response){
console.log(response);
var res = JSON.parse(response);
console.log(res);
g_form.setValue('u_phone',res.mobile_phone);
g_form.setValue('u_email',res.email);
}
}
Script include:
var sampleUtils = Class.create();
sampleUtils.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getUserDetails: function(){ //Function
var userId = this.getParameter('userId'); //Params
obj = {};
var grSysUser = new GlideRecord('sys_user');
if (grSysUser.get(userId)) {
obj.mobile_phone = grSysUser.getValue('mobile_phone');
obj.email = grSysUser.getValue('email');
}
gs.addInfoMessage(obj+JSON.stringify(obj));
return JSON.stringify(obj);
},
type: 'sampleUtils'
});
DEMO Link: https://youtu.be/nNUsfglmj_M
As an alternative to glideAjax you can EfficientGlideRecord
new EfficientGlideRecord('sys_user')
.addQuery('sys_id', newValue) //On Change client script, we will get sys_id of user in newValue variable
.addField('mobile_phone', true) //Get display value
.query(function (egrSysUser) {
if(egrSysUser.next()) {
g_form.setValue('phone', egrSysUser.getDisplayValue('mobile_phone'));
}
});
What is EfficientGlideRecord?
EfficientGlideRecord is the best alternate way to use GlideAjax.
It is a client-side API class from which you can perform asynchronous client-side GlideRecord-style queries while maximizing performance.
Benefits:
Low code configuration with Huge performance improvement.
No need to worry about security loopholes, because it enforces ACLs.
No more concerns about creating new client callable script includes and maintaining
the logic there.
Dependencies:
To use the EfficientGlideRecord we need to commit the attached update-set or find the latest version from the given link https://github.com/thisnameissoclever/ServiceNow-EfficientGlideRecord/releases.
Add the package to Portal record -> JS Includes.
and that's it, and you are good at using the EfficientGlideRecord syntax.
To know more about EfficientGlideRecord, Refer the below link(s):
https://snprotips.com/efficientgliderecord

What's the correct Protractor's syntax for Page Objects?

I've come across different types of syntax for Protractor's Page Objects and I was wondering, what's their background and which way is suggested.
This is the official PageObject syntax from Protractor's tutorial. I like it the most, because it's clear and readable:
use strict;
var AngularHomepage = function() {
var nameInput = element(by.model('yourName'));
var greeting = element(by.binding('yourName'));
this.get = function() {
browser.get('http://www.angularjs.org');
};
this.setName = function(name) {
nameInput.sendKeys(name);
};
this.getGreeting = function() {
return greeting.getText();
};
};
module.exports = AngularHomepage;
However, I've also found this kind:
'use strict';
var AngularPage = function () {
browser.get('http://www.angularjs.org');
};
AngularPage.prototype = Object.create({}, {
todoText: { get: function () { return element(by.model('todoText')); }},
addButton: { get: function () { return element(by.css('[value="add"]')); }},
yourName: { get: function () { return element(by.model('yourName')); }},
greeting: { get: function () { return element(by.binding('yourName')).getText(); }},
todoList: { get: function () { return element.all(by.repeater('todo in todos')); }},
typeName: { value: function (keys) { return this.yourName.sendKeys(keys); }} ,
todoAt: { value: function (idx) { return this.todoList.get(idx).getText(); }},
addTodo: { value: function (todo) {
this.todoText.sendKeys(todo);
this.addButton.click();
}}
});
module.exports = AngularPage;
What are the pros/cons of those two approaches (apart from readability)? Is the second one up-to-date? I've seen that WebdriverIO uses that format.
I've also heard from one guy on Gitter that the first entry is inefficient. Can someone explain to me why?
Page Object Model framework becomes popular mainly because of:
Less code duplicate
Easy to maintain for long
High readability
So, generally we develop test framework(pom) for our convenience based on testing scope and needs by following suitable framework(pom) patterns. There are NO such rules which says that, strictly we should follow any framework.
NOTE: Framework is, to make our task easy, result oriented and effective
In your case, 1st one looks good and easy. And it does not leads to confusion or conflict while in maintenance phase of it.
Example: 1st case-> element locator's declaration happens at top of each page. It would be easy to change in case any element locator changed in future.
Whereas in 2nd case, locators declared in block level(scatter across the page). It would be a time taking process to identify and change the locators if required in future.
So, Choose which one you feel comfortable based on above points.
I prefer to use ES6 class syntax (http://es6-features.org/#ClassDefinition). Here, i prepared some simple example how i work with page objects using ES6 classes and some helpful tricks.
var Page = require('../Page')
var Fragment = require('../Fragment')
class LoginPage extends Page {
constructor() {
super('/login');
this.emailField = $('input.email');
this.passwordField = $('input.password');
this.submitButton = $('button.login');
this.restorePasswordButton = $('button.restore');
}
login(username, password) {
this.email.sendKeys(username);
this.passwordField.sendKeys(password);
this.submit.click();
}
restorePassword(email) {
this.restorePasswordButton.click();
new RestorePasswordModalWindow().submitEmail(email);
}
}
class RestorePasswordModalWindow extends Fragment {
constructor() {
//Passing element that will be used as this.fragment;
super($('div.modal'));
}
submitEmail(email) {
//This how you can use methods from super class, just example - it is not perfect.
this.waitUntilAppear(2000, 'Popup should appear before manipulating');
//I love to use fragments, because they provides small and reusable parts of page.
this.fragment.$('input.email').sendKeys(email);
this.fragment.$('button.submit')click();
this.waitUntilDisappear(2000, 'Popup should disappear before manipulating');
}
}
module.exports = LoginPage;
// Page.js
class Page {
constructor(url){
//this will be part of page to add to base URL.
this.url = url;
}
open() {
//getting baseURL from params object in config.
browser.get(browser.params.baseURL + this.url);
return this; // this will allow chaining methods.
}
}
module.exports = Page;
// Fragment.js
class Fragment {
constructor(fragment) {
this.fragment = fragment;
}
//Example of some general methods for all fragments. Notice that default method parameters will work only in node.js 6.x
waitUntilAppear(timeout=5000, message) {
browser.wait(this.EC.visibilityOf(this.fragment), timeout, message);
}
waitUntilDisappear(timeout=5000, message) {
browser.wait(this.EC.invisibilityOf(this.fragment), timeout, message);
}
}
module.exports = Fragment;
// Then in your test:
let loginPage = new LoginPage().open(); //chaining in action - getting LoginPage instance in return.
loginPage.restorePassword('batman#gmail.com'); // all logic is hidden in Fragment object
loginPage.login('superman#gmail.com')

protractor first() is working and get(0) is not

There's a troncated code of a page Object in protractor
that code is working :
var HomePage = function() {
this.publishedShows = element.all(by.repeater('show in showsHomePage'));
this.getFirstShow = function(){
return this.publishedShows.first();
}
};
this one is not :
var HomePage = function() {
this.publishedShows = element.all(by.repeater('show in showsHomePage'));
this.getFirstShow = function(){
return this.publishedShows.get(0);
}
};
I get this error :
Index out of bound. Trying to access element at index: 0, but there are only 0 elements that match locator by.repeater("show in showsHomePage")
Anyone can inlight me?
It is not about get(0) vs first() - they are absolutely the same in terms of implementation. It is probably about the timing, wait for the presence of the element before making any action with it:
var elm = myPageObject.getFirstShow();
var EC = protractor.ExpectedConditions;
browser.wait(EC.presenceOf(elm), 5000);
// do smth with elm
alecxe does have a point about waiting for the element to be present and so you may want to the wait as mentioned or browser.waitForAngular();
What I have seen is that if you resolve a finder to a variable then this can get left in the unfulfilled promise state (even though the internals have resolved the query). What needs to be done is to resolve the promise and then you should be able to get the element you require:
So from your code:
`this.publishedShows = element.all(by.repeater('show in showsHomePage'));`
Will still be a promise and not publishedShows.
This returns items when I try your code (I have a slightly different repeater).
var HomePage = function() {
this.publishedShows = element.all(by.repeater('show in showsHomePage'));
this.getFirstShow = function() {
return this.publishedShows.then(function(items){
=>return items[0].getText();
});
}
};
var hp = new HomePage();
=>expect(hp.getFirstShow()).toEqual('hello');
Obviously change your expect to what you want to check for and also the return too. Marked with =>
Ensure also that if you use any track by statement then you should look at the by.exactRepeater command to have an exact match on only the repeater part.
This worked for me, note the resolved promise returns an array of finders.

How to return window.performance object to CasperJS scope

I'm trying to return window.performance object from the web page back to casper's scope with the following code but I'm getting null. Can someone explain why?
performance = casper.evaluate ->
return window.performance
#echo performance
PhantomJS 1.x doesn't implement window.performance, so you can't use it.
PhantomJS 2.0.0 implements it, but it doesn't implement the window.performance.toJSON() function. The problem with PhantomJS is that you have to access this information through evaluate(), but it has the following limitation:
Note: The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine.
Closures, functions, DOM nodes, etc. will not work!
You will have to find your own way of serializing this in the page context and passing it to the outside (JavaScript):
var performance = casper.evaluate(function(){
var t = window.performance.timing;
var n = window.performance.navigation;
return {
timing: {
connectStart: t.connectStart,
connectEnd: t.connectEnd,
...
},
navigation: {
type: n.type,
redirectCount: n.redirectCount
},
...
};
});
or look for a deep copy algorithm that produces a serializable object (from here):
var perf = casper.evaluate(function(){
function cloneObject(obj) {
var clone = {};
for(var i in obj) {
if(typeof(obj[i])=="object" && obj[i] != null)
clone[i] = cloneObject(obj[i]);
else
clone[i] = obj[i];
}
return clone;
}
return cloneObject(window.performance);
});
console.log(JSON.stringify(perf, undefined, 4));

AngularJS DOM update for loop progress

I have a number of AJAX calls that need to be run for every entry in an array, I'm trying to supply some visual feedback on the progress of the loop through the array, the model is being updated correctly but i'm not seeing anything updated in the view trying to call $digest in the loop has no effect on the DOM.
I've tried adding $apply to the function in the inner loop but I'm still seeing no change.
$scope.UploadEntry = function(item){
var oDBGet = new htmldb_Get(null,
$v('pFlowId'),
"APPLICATION_PROCESS=UploadTargetDates",
$v('pFlowStepId'));
oDBGet.add('EX_TRD',$scope.Ext.TRDDate.val);
oDBGet.add('EX_MAX_TRD',$scope.Ext.MaxTRDDate.val);
oDBGet.add('EX_READ',Ext.ReadDownloadCheck);
oDBGet.get();
};
$scope.ShowUploadModal = true;
$scope.UploadDone = 0;
for(i in submissionList)
{
$scope.UploadEntry(submissionList[i]);
$scope.UploadDone += 1;
}
$scope.ShowUploadModal = false;
But the view:
<div class="UploadModal" ng-show="ShowUploadModal">
Uploading entries: {{UploadDone}} complete
</div>
Never seen as the entries are uploaded, but does show at the end of the loop if I take the $scope.ShowUploadModal = false; out from the end of the loop.
UPDATE
After discussion, author states that the http request is synchronous. The problem is still about "sychronity", but a little bit tricker. Take a look at Angular digest concepts. It basically runs all watchers, expressions (binds) and process all $evalAsync over and over until there is no change in the watches result and expressions anymore. Just after this the DOM is updated.
So, the problem is that all your sync request are being resolved prior to the end of the digest cycle, and the DOM render will only happens after the digest cycle finishes processing.
The simplest way to solve your problem, as you state you can't change API to call async, is to ensure your requests are asynchronous, grab their promises and only hide uploadModal when all of them had been completed (this can be achieved with promises API, read promises API and $timeout). Like this:
var loadingPromises = [];
$scope.ShowUploadModal = true;
$scope.UploadDone = 0;
for(i in submissionList) {
loadingPromises.push($timeout((function(index) {
return function() {
$scope.UploadEntry(submissionList[index]);
$scope.UploadDone += 1;
};
})(i), 0));
}
$q.all(loadingPromises).then(function() {
$scope.ShowUPloadMOdel = false;
});
Note the closure I created to make sure the correct index is passed to the request, and you need to inject $q service to your controller. Although this is going to solve your problem, you should create a service and move your loading logic there, returning a promise (change your $scope references to parameters):
app.service('yourLoaderService', function($timeout) {
this.load = function(url) {
return $timeout(function() {
var oDBGet = new htmldb_Get(null,
$v('pFlowId'),
"APPLICATION_PROCESS=UploadTargetDates",
$v('pFlowStepId'));
oDBGet.add('EX_TRD',$scope.Ext.TRDDate.val);
oDBGet.add('EX_MAX_TRD',$scope.Ext.MaxTRDDate.val);
oDBGet.add('EX_READ',Ext.ReadDownloadCheck);
oDBGet.get();
}, 0);
};
});
And your controller:
var loadingPromises = [];
$scope.ShowUploadModal = true;
$scope.UploadDone = 0;
for(i in submissionList) {
var promise = yourLoaderService.load(submissionList[i]).then(function() {
$scope.UploadDone++;
});
loadingPromises.push(promise);
}
$q.all(loadingPromises).then(function() {
$scope.ShowUPloadMOdel = false;
});
First answer
This is a conception error. You seem to come from a synchronous server side background, maybe Python, I don't know. If this is your real code, then the problem is that your code is completely synchronous. You are showing upload model, looping all the entries and hiding the model and this entire code happens in milliseconds (or less) all before the DOM gets rendered even once.
This happens because when you ask for the upload, Javascript doesn't hang on the uploading process, it just asks and keep going. You can find something about async programming here, here, here and here.
You have to hook up your uploaded count in the upload callbacks. I don't know what you are using to upload, but your $scope.uploadEntry shall return a promise, then you wait it to be done and update the count.
$scope.ShowUploadModal = true;
$scope.UploadDone = 0;
for(i in submissionList)
{
$scope.UploadEntry(submissionList[i]).then(function() {
$scope.UploadDone += 1;
scope.ShowUploadModal = $scope.UploadDone !== submissionList.length;
});
}
If you're using $http for the uypload job, just return it returns, as it is already a promise and change .then(funciton per .success(function. If not, this is going to be a little more complicated, and you need to read the Angular docs on promises.
Just a side note, you should take a look at Javascript naming convetions. Javascript normally assume cammelCase variables, not PascalCase. Here's David Crackford's convetion.