Using javascript workflow library within mean stack project - javascript

I have developed a web app which is a QA forum using mean stack approach. Currently the project is working and I have implemented the basic requirements like login authentication using passportjs, then storing questions, answers, votes etc. in mongodb using mongoose.
Now I am required to add a state machine like workflow programmatically to the entire project where each module (eg.login module) will act as a state. And a flow for them must be defined.
I have looked into javascript workflow engines like workflow-4-node, bpmn.js, turbine.js. So my question is, how should I use these libraries without changing any code of my project, Is there any specific approach to do this, or am I required to change my entire code to implement the work flow.
Also in my project I am using ui.router(Routing module for angularjs) to switch between different pages and controllers (by using $stateProvider). So is this routing that I have implemented, and the state machine like workflow that I am required to do, same(different terminologies but same concept) or are they different?

NoFlo 0.8 provides a asCallback interface, allowing users to embed NoFlo graphs into existing JavaScript code.
So, if you have defined a NoFlo graph for a particular workflow, you can include it to your JavaScript app like this:
// Wrap a NoFlo graph
var myFunc = noflo.asCallback('my-project/MyGraph');
// Call the wrapped graph
myFunc({
inport: 'data'
anotherport: 'more data'
}, function (err, result) {
// Do something with the result
});

Related

Using existing cljs components in a React project?

https://www.reddit.com/r/Clojure/comments/4el0xi/how_to_use_an_existing_reactjs_component_with/
There is this existing post about using existing ReactJS components in a CLJS/Reagent project. I'm looking to do the opposite. I have a bunch of CLJS components and would like to compile them into a ui library of some sort so that they can be used by React developers. That is, if I have a button CLJS component, I would like to be able to render that Button using < Button /> or mylib.Button(_) etc.. in a React/js app file.
I have read this - https://shadow-cljs.github.io/docs/UsersGuide.html#target-node-library - extensively but it's not quite working out. I've been using ":target :node-library" and I can get simple functions (that return strings/numbers, for example) to compile and work in my app, etc.. but it doesn't work for entire components. For example, my cljs button component takes in :
defn button [props & children]
but when I try to pass in these parameters (I call {lib.button({}, {})} in my App.js file), I get errors like "No protocol method IMap.-dissoc defined", because I'm trying to pass JS objects into CLJS-only functions, I believe. Not sure how to resolve this..
I can explain more on this if it would help clarify. It would also be super helpful if anyone had a reference demo project or any resources they could link me to.
I only have a few suggestions:
You can try to build a new sample project to consume your library with lein new figwheel myproject and use JavaScript interop to move one step at a time closer to the native JS way of using your library.
You can create an interface namespace that can consume JS objects and wrap these into Clojure data structures to sort out the protocol errors you're seeing, eg. functions that take a props parameter and pass down (js->clj props) to the rest of the code underneath.
For the authoritative source, check the Reagent docs, especially this: http://reagent-project.github.io/docs/master/InteropWithReact.html#creating-react-components-from-reagent-components

Can I use Laravel's "Service Container pattern" in JavaScript?

So, let's say that I am building a single-page app in JavaScript. For now I do not have a persistence layer in my app but I still need to write the code.
class App {
handleClick(event) {
User.saveToFile(event.target.value);
}
render() {
return 'Some template...';
}
}
So, I create my concrete user class. But for now just save it to the local storage.
class User {
constructor(localStorageHelper) {
this.localStorageHelper = localStorageHelper;
}
save(name) {
this.localStorageHelper.users.save({
name
});
}
}
When the database is ready, I need to switch to the database. If I was in an object-oriented language I can simply create an interface and use polymorphism or repository pattern to solve this problem.
I was wondering what if I create an app container to contain all of the concrete implementations. For example I can create a bindings.js file like the following:
import UserPersister from './Repos/Db/User'
import PostPersister from './Repos/File/Post'
const Bindings = {
'UserPersister': UserPersister,
'PostPersister': PostPersister
};
So now in my App.js file. I can do something like:
let User = Container.make('UserPersister');
class App {
handleClick(event) {
User.saveToFile(event.target.value);
}
render() {
return 'Some template...';
}
}
Now I can easily switch between different implementations by just changing them in bindings.js. If you've worked a little bit with Laravel this should seem familiar (except for the service providers of course).
This sounds OK to me but I am not sure if it is ACTUALLY OK to do this sort of thing in JavaScript. What advice would you give based on your experience with JavaScript?
If you want to reproduce laravel's pattern - that can be hard - but I can suggest you two technologies that can helps you with it. When you combained them you can easily implement quite similar code conception.
1 TypeScript
In fact you're using it in above code. It's a kind of JavaScript wrapper in which you can write a code similar to Java solutions. You have access here to polymorphism, inheritance and encapsulation like in typical PHP OOP. This can speed up your work a bit and it's pure and it's uses ECMAScript 2015.
2 AngularJS
The large JS Framework which is very strong and have big community. This one privides you for example injection service (like Laravel's IoC) which will automaticcly resolve all your dependencies. You can create easily repositories using $resources which is ajax wrapper for REST API requests. There are service providers that works greate on application load. And the best is that - yo can build one-page-application with Angular. It have many other advanteges. There is stable version 1 and unstable verison 2 which is developed in TypeScript.
With these two tools you can build awesome stuff for the frontend (client side). If you want more tools here it is:
PuppetJS - server side generating client side JS scripts (one implementation fort both sides!).
React - great library based on components

Event-based communication with an AngularJS BackgroundServicesApp on a seperate HTML document

Scenario:
I'm building an AppGyver Steroids mobile web app.
I chose to build a Multi Page Application using multiple WebViews to display parts of my app, because that way I can use native tabs, header bars and page transitions.
My JavaScript framework is AngularJS.
Since every WebView has its own DOM and JavaScript runtime, my AngularJS services are no unique singletons. This creates problems.
Appgyver suggests to load a hidden backgroundServices.html document as an always-there master document and house the singletons in my app there.
They provide a publisher/subscriber method using
window.postMessage("someMessage");
and
window.addEventListener("message", someMethod);
to communicate between WebViews.
Unfortunately they provide no example of this method and I'm really struggling to build a clean implementation.
Since I'm using Restangular I would like my REST services (that should be in backgroundServices) to return promises, and I can't figure out how to do that in a reusable way with a publisher/subscriber mechanism in between, without causing too much overhead..
How can I communicate with an AngularJS service only accessible using Events, and keep working with Promises?
I figure I need to make a "BackgroundServiceConnector" service available on every normal webview.
In this Service I would have a function
call(serviceName, function, parameters)
which I call like this:
var app = angular.module('homeApp', ['ngTouch', 'BackgroundServiceConnectorApp']);
app.controller('LoginCtrl', function ($scope, backgroundServiceConnector) {
$scope.doLogin = function(username, password){
backgroundServiceConnector("accountService", "authenticate", {username: username,password: password})
.then(function(){
//login OK logic
}, function(error){
//login Not OK logic
});
}
});
I think I'm more or less capable of implementing this, but I am unsure of:
how to make this usable for functions that do not return promises. (detect if the function returns a promise at the backgroundServices.html side)
if there isn't a more elegant way in which I don't have to pass "accountService" and "authenticate" as strings.
how I can - in the backgroundServices.html - parse the service name and function into an executable call.
how would I go about making the foreground services automatically "subscribe" to changes in the "model" at the background?
I know enough JavaScript to know it is a very extensible language offering a lot of freedom, but I don't know enough to be able to build a good solution for my scenario..
I would love for someone to help point me in the right direction and provide advice.
Thanks!

Meteor modify auth smart package

How do I modify the auth smart package?
For example the dropdown box after registering show the buttons change password and sign out. I want to add an edit account button. How?
Thanks.
To add an edit button, look here:
https://github.com/meteor/meteor/tree/master/packages/accounts-ui-unstyled
Specifically, the login_buttons.html file.
update: There's a note at the top of the linked file:
NOTE: You shouldn't use these templates directly. Instead, use the
global {{loginButtons}} template.
Thus, you should find these files in your meteor installation (mine is in C:\Program Files (x86)\Meteor\packages\accounts-ui\login_buttons.html) and edit that file.
Note this will modify the accounts UI for all your meteor apps. If you do not want your changes to affect your other meteor apps, you will probably have to "fork" your own accounts-ui package.
There is discussion of making the accounts UI more customizable (like overridable templates), but it is not possible with the current version of Meteor. I suggest describing your use case to the meteor developers. The meteor developers openly welcome feedback:
Feedback, please! Some specific areas that we're curious about:
What sort of customization do you want to do to the loginButtons template?
What sort of account restrictions are you likely to use? Everyone must have a username? Everyone must have an email?
You can override the loginButtons, because currently the default helpers object is public for some reason:
Handlebars._default_helpers["loginButtons"] = function(options) {
return "hello this is test";
};
The original helper function looks like this:
Handlebars.registerHelper(
"loginButtons",
function (options) {
if (options.hash.align === "right")
return new Handlebars.SafeString(Template._loginButtons({align: "right"}));
else
return new Handlebars.SafeString(Template._loginButtons({align: "left"}));
});
Here you could replace the default _loginButtons template with your own.
However this could easily break with a future version of meteor as Handlebars._default_helpers is not really intended to be used in that way. But at least you don't have to work with a fork of meteor.
Also you have to make sure that you add your helper after accounts-ui-unstyled does. So if you are using this trick inside another package, be sure to declare accounts-ui-unstyled as a dependency.

Test-driven development of JavaScript web frontends

This might sound a little dumb, but I'm actually a bit confused how to approach JavaScript testing for web frontends. As far as I'm concerned, the typical 3-tier architecture looks like this:
Database tier
Application tier
Client tier
1 is of no concern in this question. 2 contains all the program logic ("business logic") 3 the frontend.
I do test-driven development for most projects, but only for the application logic, not the frontend. That is because testing the UI is difficult and unusual in TDD, and normally not done. Instead, all application logic is separated from UI, so that it is simple to test that logic.
The three tier architecture supports this: I can design my backend as a REST API which is called by my frontend. How does JS testing fit in? For the typical three-tier-architecture, JS (i.e. JS on the client) testing doesn't make much sense, does it?
Update:
I've changed the question's wording from "Testing JavaScript in web frontends" to "Test-driven development of JavaScript web frontends" to clarify my question.
Remember what the point of unit-testing is: to ensure a particular module of code reacts to some stimuli in an expected manner. In JS, a significant portion of your code, (unless you have some lifecycle framework like Sencha or YUI) will either be directly manipulating the DOM or making remote calls. To test these things, you simply apply traditional unit-testing techniques of dependency injection and mocking/stubbing. That means you must write each function, or class, that you want to unit-test to accept mocks of the dependent structures.
jQuery supports this by allowing you to pass an XML document into all traversal functions. Whereas you might normally write
$(function() { $('.bright').css('color','yellow'); }
you'll instead want to write
function processBright(scope) {
// jQuery will do the following line automatically, but for sake of clarity:
scope = scope || window.document;
$('.bright',scope).css('color','yellow');
}
$(processBright);
Notice we not only pull the logic out of the anonymous function and give it a name, we also make that function accept a scope parameter. When that value is null, the jQuery calls will still function as normal. However, we now have a vector for injecting a mock document that we can inspect after the function is invoked. The unit-test could look like
function shouldSetColorYellowIfClassBright() {
// arrange
var testDoc =
$('<html><body><span id="a" class="bright">test</span></body></html>');
// act
processBright(testDoc);
// assert
if (testDoc.find('#a').css('color') != 'bright')
throw TestFailed("Color property was not changed correctly.");
}
TestFailed could look like this:
function TestFailed(message) {
this.message = message;
this.name = "TestFailed";
}
The situation is similar with remote calls, though rather than actually injecting some facility, you could get away with a masking stub. Say you have this function:
function makeRemoteCall(data, callback) {
if (data.property == 'ok')
$.getJSON({url:'/someResource.json',callback:callback});
}
You would test it as such:
// test suite setup
var getJSON = $.getJSON;
var stubCalls = [];
$.getJSON = function(args) {
stubCalls[stubCalls.length] = args.url;
}
// unit test 1
function shouldMakeRemoteCallWithOkProperty() {
// arrange
var arg = { property: 'ok' };
// act
makeRemoteCall(arg);
// assert
if (stubCalls.length != 1 || stubCalls[0] != '/someResource.json')
throw TestFailed("someResource.json was not requested once and only once.");
}
// unit test 2
function shouldNotMakeRemoteCallWithoutOkProperty() {
// arrange
var arg = { property: 'foobar' };
// act
makeRemoteCall(arg);
// assert
if (stubCalls.length != 0)
throw TestFailed(stubCalls[0] + " was called unexpectedly.");
}
// test suite teardown
$.getJSON = getJSON;
(You can wrap that whole thing in the module pattern to not litter the global namespace.)
To apply all of this in a test-driven manner, you would simply write these tests first. This is a straightforward, no frills, and most importantly, effective way of unit-testing JS.
Frameworks like qUnit can be used to drive your unit-tests, but that is only a small part of the problem. Your code must be written in a test-friendly way. Also, frameworks like Selenium, HtmlUnit, jsTestDriver or Watir/N are for integration testing, not for unit-testing per se. Lastly, by no means must your code be object-oriented. The principles of unit-testing are easily confused with the practical application of unit-testing in object-oriented systems. They are separate but compatible ideas.
Testing Styles
I should note that two different testing styles are demonstrated here. The first assumes complete ignorance of the implementation of processBright. It could be using jQuery to add the color style, or it could be doing native DOM manipulation. I'm merely testing that the external behavior of the function is as expected. In the second, I assume knowledge of an internal dependency of the function (namely $.getJSON), and those tests cover the correct interaction with that dependency.
The approach you take depends on your testing philosophy and overall priorities and cost-benefit profile of your situation. The first test is relatively pure. The second test is simple but relatively fragile; if I change the implementation of makeRemoteCall, the test will break. Preferably, the assumption that makeRemoteCall uses $.getJSON is at least justified by the documentation of makeRemoteCall. There are a couple more disciplined approaches, but one cost-effective approach is to wrap dependencies in wrapper functions. The codebase would depend only on these wrappers, whose implementations can be easily replaced with test stubs at test-time.
There is a book titled Test-Driven JavaScript Development by Christian Johansen that might help you. I have only looked at some of the samples in the book (just downloaded a sample to Kindle the other day) but it looks like a great book that addresses this very issue. You might check it out.
(Note: I have no connection with Christian Johansen and no investment in sales of the book. Just looks like a good thing that addresses this problem.)
I have a similary architected application with JS client tier. In my case i use our company's own JS-framework to implement client tier.
This JS framework is created in OOP-style thus i can implement unit-testing for core classes and components. Also, to cover all user interactions (which can't be covered using unit-testing) i am using Selenium WebDriver to do an integration testing of framework visual components and test them under different browsers.
So, TDD can be applied to JavaScript development if code under test is written in OOP-manner. Also integration test is also possible (and can be used to do some kind of TDD).
Have a look at QUnit, as well, for unit tests of JavaScript methods and functions.
You can test your application from a user perspective with tools such as Rational Functional Tester, the HP tools or other equivalent software.
These tools test the application as if a user was sitting in front of it, but in an automated fashion. This means that you can test all three tiers at the same time, and especially the Javascript which may be difficult to test otherwise. Functional testing like this may help to find UI bugs and quirks with how the UI is using the data pushed out by your middle tier.
Unfortunately these tools are very expensive, so there may be other equivalents (and I'd be interested to know of such tools).
In our company we use jsTestDriver. It's a feature rich environment for testing frontend.
Take a look at it.

Categories

Resources