Tag Archives: MEAN Stack

BazaarJS: our criticisms of Angular


BazaarJS: our criticisms of Angular
// Il Blog di Cantiere Creativo

Angular describes itself as a toolkit for improving HTML, one which makes it possible to extent HTML itself using new vocabulary known as directives. Directives transform a static document into a dynamic template, thereby minimizing — and sometimes eliminating entirely — the need to write Javascript code.

Angular is without any doubt the most popular front-end framework amongst those currently available on the market and is supported by a internal Google team, giving it instant credibility. It is so popular that it deserves its own acronym… and in fact forms part of the MEAN stack, composed of MongoDB, Express, AngularJS and Node. It is no accident that knowledge of Angular is a skill currently particularly sought after on the job market.

Here at LeanPanda, we’ve been working with Angular for almost nine months now (the original article in italian is dated February 2015): enough time for us to have a gotten a reasonably complete picture of its advantages and disadvantages. Rather than produce yet another Angular tutorial, we have decided to get straight to the point and set out what we see as the major criticisms of the framework.

Problem #1: Scope inheritance and dynamic scoping

This is without doubt the most frequent and unnerving problem for any developer who finds themself using Angular. Let’s take these lines of code as a reference point:

<input type="text" ng-model="obj.prop" />

Question: in the second input tag, does obj.prop refer to the same variable as the first input? The answer, unfortunately, is that it is impossible to say with certainty just by reading the code. It depends on the state of the program at runtime. You don’t believe us? Try it for yourself: if you start writing inside the first input, the variable will be shared by both of them. If you start writing inside the second input, the two will be independent.

How is that possible? It’s caused by the way in which Angular manages variable scoping. ng-if is a directive that introduces a new scope, which prototypically inherits the most external scope.

Writing for the first time in the first input, the obj.prop variable is initialized with external scope, meaning that — thanks to prototypical inheritance — it is also propagated with internal scope. And vice-versa by writing for the first time in the second input, the variable is initialized internally with internal scope without having external scope.

Simplifying and abstracting the concepts in play from the details of the Angular implementation, we get something like this:

Every time I find myself with the (unsought after) task of having to explain this situation to new developers I can’t help asking myself: “Is there any reason for this?” Fortunately, I don’t have to come up with the answer all by myself: the topic has been formalized and discussed for decades.

Lexical scoping is defined as scoping that can be determined by reading the source code alone. When, on the contrary, scoping depends on the state of the programme, it is defined as dynamic scoping. Returning to our question, the response that dozens of people have given is “No: dynamic scoping doesn’t make any sense at all”. Almost all modern languages implement lexical scoping, because its far more predictable and easier to manage.

Problem #2: Dirty checking

Angular supports so-called data-binding. That is, the ability to connect fragments of the DOM to Javascript variables. Once a binding has been imposed, it is possible for a modification to a variable to have an impact on the DOM without any intervention on the part of the developer.

Angular certainly isn’t the only framework to support this concept: the particularity lies in the way in which Angular achieves this result. Let’s suppose we want to generate a simple timer:

The modification of the value of a scope variable is propagated on viewing only after Angular has been notified of the desire to apply it by means of metodo $scope.$apply(). To avoid filling the application code with these kinds of calls, Angular makes a comprehensive library of objects the only scope of which is to call $scope.$apply() to our location at the correct time. In our case, we can make use of the $interval service:

Imposing service as $interval from above in this way is questionable in and of itself, but the fundamental problem is the following: Angular, not knowing precisely which and how many variables have been changed when the final phase of rendering carried out, is forced to carry out a dirty-check of every binding activity in the page, to identify any values that differ from those previously saved on viewing. In the case of such changes being present, the associated change-listeners are triggered, which may themselves cause changes to the scope! In this fashion, the process repeats itself until an absence of changes has been detected.

You don’t need a masters in computer science to realize that this results in an extremely costly and non-optimized operation. A single minor modification to the scope can trigger many hundred or thousands of checks within the application. It is for this reason that the Angular community has always maintained that it is good practice to limit the total number of bindings present in an application to 2000. If this threshold is breached, good performance can no longer be guaranteed.

To avoid any misunderstanding, it’s important to bear in mind that this set-up was a conscious choice made by the Angular team, who were trying to find an “acceptable” trade-off between performance and ease of writing for developers. The problem is that it’s very easy to go over this theoretical limit in applications of average complexity, and up until version 1.3 of Angular, there weren’t any official alternatives in place to work around the problem.

ECMAScript 7 introduces the Object.observe() method, which is able to hook change-listeners onto the value changes in simple Javascript objects, offering a better-performing alternative to the current dirty-checking approach… but we still don’t even have a possible publication date for the new standard, so it’s anyone’s guess as to when the functionality will actually be implemented in-browser.

Problem #3: Dependency injection

Amongst Angular’s most striking features is the fact that it brings with it its own system of dependency management, based on the concept of dependency injection:

var myApp = angular.module('MyApp', []); myApp.factory('sum', function() { return function(a, b) { return a + b; }; }); myApp.controller('MyCtrl', function ($scope, sum) { $scope.foo = sum(1, 3); }); 

The Angular injector is able to carry out introspection on the names of the parameters passed to the functions that define a module, and to make their related dependencies available.

So, what’s the problem? Well, in a previous article we have already explained the details of Javascript’s two standard module loading mechanisms: CommonJS/AMD. Angular forces you to use a third, custom designed alternative mechanism: one that is inferior to the already existing mechanisms available.

Angular’s system of dependency injection starts to get tiring as soon as you begin minimizing your code, and find yourself forced to invent an uncomfortable alternative syntax to manage the problem. And, more importantly, it makes it entirely impossible for tools like Browserify or Webpack to do what they were designed to do:

  • manage the dependencies of Angular and other third party applications (such as Bower and npm) inside our application;
  • subdivide our application’s code into bundles that can be downloaded by the client asynchronously.

Problem #4: Pointless complexity

I remember very well the feeling of depression and suffering that I experienced during the first (of countless) visits I have made to the Angular service objects page. Oh dear God… providers, values, factories, services, constants…? What’re they for? Why do you need 2000 lines and 5 different modes to define an ordinary Javascript logic module?

After days of research and experimentation I came to the tragic conclusion that there aren’t any major differences between them: they’re all pretty much the same thing. All five concepts could easily be assigned a single identity. I’m not joking: we were perfectly able to get by in one of the Angular projects developed internally — consisting of around 200 Javascript files and a total of around 10,000 lines of code — using only factories.

This is not the only way in which Angular seems to be wilfully trying to be as incomprehensible as possible. Other examples?

  • What does it mean to create an E directive or an A directive? Never mind an EA directive?
  • Surely there is a more intelligible and semantically coherent way of describing the modality of a variable’s bindings than using symbols like =, &, =* and @?

Problem #5: Server-side rendering

Angular’s choice to use a page’s HTML content as a templating language — using “directives” embedded in the form of classes, attributes or tags — in addition to presenting an ample number of “minor” problems, also brings with it one insurmountable obstacle: the inability to produce isomorphic applications.

A large part of the logic of an Angular application resides in the HTML of the webpage itself, in the form of ng-ifs, ng-repeats and suchlike. This means that it is simply impossible to make an Angular application work server-side, by design.

Services like prerender.io make it possible to get around the problem, but the result is most certainly a workaround; one which can itself give rise to problems related to cache-expiration.

Problem #6: Angular 2

Not convinced yet? Well, what if we were to tell you that the next major version of Angular will take a scorched earth approach to the existing structure that means it will have zero retro-compatibility with what exists today?

Five years after its first public release, the developers of Angular have learnt a lot of lessons and realized that the abstractions that the framework is based on today are insufficient and confused. They have therefore made the decision, which they announced at ng-conf, to write the next major version of the framework from scratch.

This is a courageous choice, and all considered an entirely laudable one, given that Google have in any case guaranteed a long period of maintenance for Angular 1.x. We faithfully await the publication of this new project (which will probably share only its name with Angular’s current instantiation)… in the meantime, however, it would be simply foolish to use Angular 1.x for new applications.

Conclusions

Despite the unflattering words we have so far used to discuss Angular, it is important to underline that the framework nonetheless provides an acceptable option for the production of client-side applications.

Its huge popularity has led to the creation of an enormous number of third party modules, which can be extremely useful for quickly putting together working prototypes.

Once you’ve got past the initial learning curve, have found you own “formula” for structuring code and have learnt how to manage the idiosyncrasies of directives, scopes and ng-models, Angular offers you everything you need to be able to build applications within acceptable time-frames.

Let’s now return to fundamental question: is it worth it? The answer is “no”, at least for us. That said, we don’t just want to be negative, so we feel we ought to offer you an explanation of what we think is a valid alternative.

Next episode? React!

With the next article we’re going to introduce you to React JS, which takes an approach to the problem of SPA construction that is entirely different to the one taken by Angular — or any other library or framework developed in the past — and is in many ways a creature entirely alien to the world of Javascript. Alien enough to have won us over entirely.

Follow us on Twitter or subscribe to our RSS feed to keep up to date!

MEAN Stack: Node ToDo List App with Mongodb


MEAN Stack : Node ToDo List App with Mongodb
// Kogonuso

My Todo List {{ todos.length }}
{{ todo.text }}

MEAN Stack : Authentication with Passport


MEAN Stack : Authentication with Passport
// Kogonuso

sshot-10529.png

Node.JS

Passport is authentication middleware for Node. It is designed to serve a singular purpose: authenticate requests.
In modern web applications, single sign-on using an OAuth provider such as Facebook or Twitter has become a popular authentication method. Services that expose an API often require token-based credentials to protect access.
Passport recognizes that each application has unique authentication requirements. Authentication mechanisms, known as strategies, are packaged as individual modules. Applications can choose which strategies to employ, without creating unnecessary dependencies.

app.post('/login', passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/login' }));

Express generator
With express 4 the express boilerplate generator command line was extracted to it’s own module express-generator because the generator app did not really share code with express web framework and express and generator app can be released independently.
To generate a basic project boilerplate, we’ll start by installing the Express generator:

$ npm install -g express-generator@4

The -g flag means that we’re installing this globally, on our entire system.
passport-local
Let’s create a project – passport-local:

$ express passport-local

package.json – dependencies
Let’s install dependencies:

{
"name": "passport-local",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"repository": {
"type": "git",
"url": "git@github.com:epic-math/NodeJS-MEAN.git"
},
"author": "K Hong

With the package.json, let’s install dependencies:

$ pwd
/home/ubuntu/passport-local
$ sudo npm install

testing app
We can test our setup by running the app:

$ node /home/ubuntu/passport-local/bin/www

We may want to navigate to http://localhost:3000/ in the browser (in our case, http://54.67.103.65:3000/), and we should be able to see the “Welcome to Express” text staring back.

MongoDB install
Let’s install MongoDB:

$ sudo npm install -g mongodb
$ sudo service mongod start

app.js update
Here is the updated app.js:

// dependencies
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('express-session')({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
// passport config
var Account = require('./models/account');
passport.use(new LocalStrategy(Account.authenticate()));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());
// mongoose
mongoose.connect('mongodb://localhost/passport_local_mongoose_express4');
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;

Mongoose – models/account.js
Let’s get the Mongoose up and running. Add a new file, models/account.js with the following code:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var Account = new Schema({
username: String,
password: String
});
Account.plugin(passportLocalMongoose);
module.exports = mongoose.model('Account', Account);

We can test our setup again by running the app:

$ node /home/ubuntu/passport-local/bin/www

We may want to navigate to http://localhost:3000/ in the browser (in our case, http://54.67.103.65:3000/), and we should be able to see the “Welcome to Express” text staring back.

routes/index.js
Now we want to modify routes/index.js:

var express = require('express');
var passport = require('passport');
var Account = require('../models/account');
var router = express.Router();
router.get('/', function (req, res) {
res.render('index', { user : req.user });
});
router.get('/register', function(req, res) {
res.render('register', { });
});
router.post('/register', function(req, res) {
Account.register(new Account({ username : req.body.username }), req.body.password, function(err, account) {
if (err) {
return res.render('register', { account : account });
}
passport.authenticate('local')(req, res, function () {
res.redirect('/');
});
});
});
router.get('/login', function(req, res) {
res.render('login', { user : req.user });
});
router.post('/login', passport.authenticate('local'), function(req, res) {
res.redirect('/');
});
router.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
router.get('/ping', function(req, res){
res.status(200).send("pong!");
});
module.exports = router;

To test, let’s fire up the server:

$ node /home/ubuntu/passport-local/bin/www

We may want to navigate to http://localhost:3000/ping in the browser (in our case, http://54.67.103.65:3000/ping), and we should be able to see the “pong!” text staring back.

views/layout.jade

doctype html
html
head
title= title
meta(name='viewport', content='width=device-width, initial-scale=1.0')
link(href='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css', rel='stylesheet', media='screen')
link(rel='stylesheet', href='/stylesheets/style.css')
body
block content
script(src='http://code.jquery.com/jquery.js')
script(src='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js')

views/layout.jade

doctype html
html
head
title= title
meta(name='viewport', content='width=device-width, initial-scale=1.0')
link(href='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css', rel='stylesheet', media='screen')
link(rel='stylesheet', href='/stylesheets/style.css')
body
block content
script(src='http://code.jquery.com/jquery.js')
script(src='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js')

views/index.jade

extends layout
block content
if (!user)
a(href="/login") Login
br
a(href="/register") Register
if (user)
p You are currently logged in as #{user.username}
a(href="/logout") Logout

views/login.jade

extends layout
block content
.container
h1 Login Page
p.lead Say something worthwhile here.
br
form(role='form', action="/login",method="post", style='max-width: 300px;')
.form-group
input.form-control(type='text', name="username", placeholder='Enter Username')
.form-group
input.form-control(type='password', name="password", placeholder='Password')
button.btn.btn-default(type='submit') Submit

a(href='/')
button.btn.btn-primary(type="button") Cancel

views/register.jade

extends layout
block content
.container
h1 Register Page
p.lead Say something worthwhile here.
br
form(role='form', action="/register",method="post", style='max-width: 300px;')
.form-group
input.form-control(type='text', name="username", placeholder='Enter Username')
.form-group
input.form-control(type='password', name="password", placeholder='Password')
button.btn.btn-default(type='submit') Submit

a(href='/')
button.btn.btn-primary(type="button") Cancel

Here is the test for “register”.

At “Submit”, we get:

If we click “Logout”:
If we use the registered user’s credential to log back in:

After hitting “Submit, we get:
Checking with mongodb
Let’s check our MongoDB:

$ mongo
MongoDB shell version: 3.0.6
connecting to: test
Welcome to the MongoDB shell.
...
> use passport_local_mongoose_express4
switched to db passport_local_mongoose_express4
> db.accounts.find()
{ "_id" : ObjectId("561...555"), "salt" : "7c24...304", "hash" : "a6a46371
...
23c3", "username" : "epicmath", "__v" : 0 }
>

We can see the following from the the check with the db:

  • username is as we expected – “epicmath”
  • _id pertains to the unique id associated with that document.
  • __v is the version # for that specific documents.
  • Instead of a password key, we have both a salt and a hash key.

Creating a Web App with MATLAB and the MEAN Stack


Creating a Web App with MATLAB and the MEAN Stack
// Kogonuso

{{data.hours}} : {{data.minutes}} : {{data.seconds}}

MEAN WEB DEVELOPMENT | Author Sander Rossel


So what is MEAN? I could call you dumb for not knowing, that would be mean (and unjustified, because you’ll know within seconds), but that’s not quite the mean I’m talking about! MEAN is actually an acronym (because we love acronyms in IT) and it stands for MongoDB, Express, AngularJS and Node.js. Chances are you’ve heard of those and if you read a previous blog post of mine, Web development #8: Where to go from here, you even know a little bit about what they are (although you could’ve got that from other sources too, of course).
In short, MongoDB is a NoSQL Document Model database, Node.js is a platform that allows you to run JavaScript on/as your web server, Express is a library that simplifies working with Node.js and AngularJS is a front end framework that let’s you create Single Page Applications (SPAs).

Don’t worry, we’ll look at all of them in much more detail later. In fact, I’ve already written on MongoDB in an earlier blog post, A first look at NoSQL and MongoDB in particular. Actually I’m going to ask you to read that post in a little bit.

So here’s the deal, MongoDB is a database that doesn’t use SQL, but JavaScript, as a query language, Node.js is a platform that let’s you use JavaScript on your back end, AngularJS is a JavaScript library for your front end and Express is just a library for Node.js. So that’s JavaScript across your entire stack! That’s pretty awesome, especially when you’re a fan of JavaScript.

You’re probably going to use more than just MEAN. MEAN is just a starting point, but, of course, you’re free to add (or remove) whatever you like. Perhaps a little jQuery UI, a HTML generator like Jade,  or sockets.io, a library for working with sockets in Node.js.

Introduction to the MEAN Stack


via Introduction to the MEAN Stack.

It was a long time ago since the acronym LAMP (Linux Apache MySql PHP) was created. Today another very common stack is the MEAN stack. Probably not all of you know what that the acronym “MEAN” stands for, so let’s start with the basic. MEAN stands for MongoDB, Express, AngularJS and Node.js. It deals with a full stack JavaScript solution for building websites and web applications. From the database to the back-end code and the front-end code, everything is written using JavaScript. In case you aren’t familiar with the technologies used by the MEAN stack, you can find a short introduction about these technologies in the following section.

You can find the whole source code for this article on GitHub. Feel free to fork it and play around with it.

Running a MEAN web application in Docker containers on AWS


via Running a MEAN web application in Docker containers on AWS | via @codeship.

The rate of adoption of Docker as a containerized solution is soaring. A lot of companies are now using Docker containers to run apps. In a lot of scenarios, using Docker containers can be a better approach than spinning up a full-blown virtual machine.

In this post, I’ll break down all the steps I took to successfully install and run a web application built on the MEAN stack (MongoDB, Express, AngularJS, and Node.js). I hosted the application in Docker containers on Amazon Web Services (AWS).

Also, I ran the MongoDB database and the web application in separate containers. There arelots of benefits to this approach of having isolated environments:

  1. Since each container has its own runtime environment, it’s easy to modify the environment of one application component without affecting other parts. We can change the installed software or try out different versions of the softwares, until we figure out the best possible setup for that specific component.
  2. Since our application components are isolated, security issues are easy to deal with. If a container is attacked or a malicious script ends up being inadvertently run as part of an update, our other containers are still safe.
  3. Since it is easy to switch out and change the connected containers, testing becomes a lot easier. For example, if we want to test our web application with different sets of data, we can do that easily by connecting it to different containers set up for different database environments.