Sign up to get extra content & updates via email!

Thanks for signing up!
I appreciate it!

Generating with MeanJS and Yeoman Generator


One of my favorite things with Yii is the Gii (Generator).
With a few clicks I could simply add a few Models/Controllers/Views (or all of the above), then build/customize those.

MeanJS uses the Yeoman/Yo generator to make this happen.
After installing Yeoman generator (which I believe we already installed when we installed MeanJS) via:

npm install -g yo

Now to install the MeanJS generator package:

npm install -g generator-meanjs

(remember, often when running npm install -g you’ll need to sudo it)

Basic CRUD

For those who are not familiar with the concept, CRUD stands for – Create, Read, Update & Delete.
These are the basics one needs to present & manipulate data on a website, and a lot of web frameworks generate CRUDs as sort of a first-step.
Let’s create our first CRUD:

yo meanjs:crud-module firstmodule

After selecting the supplemental folder to include in the Angular Module, and whether or not the module should be added to the menu, a bunch of files are generated.
Very Important: The crud-module generates both the Server side & Client files.

The Module Structure was explained thoroughly on Basics of MeanJS.

The crud-module is the all encompassing, there are also sub generators:

  • angular-module
  • angular-route
  • angular-controller
  • angular-view
  • angular-service
  • angular-directive
  • angular-filter
  • angular-config
  • angular-test
  • express-model
  • express-controller
  • express-route
  • express-test

Those names are pretty self explanatory, so I don’t see much need to go deeper there.

More information about Yeoman generator specifically used for MeanJS can be found here

As you can probably notice, this article came out a bit shorter than expected, this is mainly due to time constraints.

I’d like to continue and develop under MeanJS, as I see a lot of interest on the subject.

There are also a few other frameworks that I started reading about that might be a part of some future articles (some are fairly similar).

Bonus info: MeanJS was on the Changelog podcast!, very cool.

Tagged with: , , , , ,
Posted in Uncategorized

Random Tips for programmers

This week I wasn’t able to continue my writing about MeanJS (relocation takes a LOT of your otherwise free time apparently).

So I’ve assembled a short list of some tips learned in the past few weeks:

Github’s quick file search

When looking for a specific file on a repository that’s also stored on Github, it might be easier to search for the files on the website (especially if you’re dealing with a lot of different branches, easier than switching between all of them locally).

I’ve recently learned that there’s a quick file search option, that can save you a LOT of time.
On the repository view, simply press “T”, you should get the following screen:

For example, searching for main.css:

For extra Shortcuts, here’s a small cheat sheet from github:

Learn the powers of git log

and just about every git command is incredibly powerful

I had to review a branch recently after merging it, sadly github doesn’t give many tools to filter through commits and I wanted to see what was committed into the branch, without all the merged commits.
The command I ended up using was:

git log --first-parent

That way I only saw the direct commits on the branch, very useful.
If you also want to see what has changed within those commits, simply run:

git log -p -m --first-parent

There is a lot to learn within git log (much like in every command on git).

Event Listener Breakpoints

Let’s say you’re debugging a relatively complex JS website, and you’re trying to grab the event attached to some button.
It has been years since Inspectors (Chrome/Firebug) were able to show coherent Event Listeners, but because of jQuery/Backbone/whatever you are using it’s impossible to gather relevant information there (honestly that should be fixed).
In come Event Listener Breakpoints:

The most common event is obviously the ‘click’ event, that is very useful to track what functions are being called without having to put breaks everywhere.

That’s it for this week, I know the post is short but I’m going to try to add some extra time next week to write a coherent post.

Tagged with: , , ,
Posted in Uncategorized

Testing on MeanJS


This time I’ll be covering the testing done on the Backend (Mocha) and Frontend (Karma).

Mocha

Mocha is a JS testing framework that allows Test-Driven Development (TDD) and Behavior-Driven Development (BDD) approaches to be used for building the tests.
There’s a lot to learn about Mocha, luckily it’s very well documented. Let’s walk through the examples that are given in MeanJS (inside app/tests). article.server.model.test.js

describe('Article Model Unit Tests:', function() {
	beforeEach(function(done) {
		user = new User({
			firstName: 'Full',
			lastName: 'Name',
			displayName: 'Full Name',
			email: 'test@test.com',
			username: 'username',
			password: 'password'
		});

		user.save(function() {
			article = new Article({
				title: 'Article Title',
				content: 'Article Content',
				user: user
			});

			done();
		});
	});

	describe('Method Save', function() {
		it('should be able to save without problems', function(done) {
			return article.save(function(err) {
				should.not.exist(err);
				done();
			});
		});

		it('should be able to show an error when try to save without title', function(done) {
			article.title = '';

			return article.save(function(err) {
				should.exist(err);
				done();
			});
		});
	});

	afterEach(function(done) {
		Article.remove().exec();
		User.remove().exec();
		done();
	});
});

The thing I love about Mocha is the readability of the test code, most functions are self explanatory.

The line with beforeEach calls the function that follows, before every test within the current test suite. As you can probably guess, we’re creating a dummy User & Article and connecting the Article to the User. If we skip the test itself and look at afterEach, it’s pretty easy to understand that we’re erasing the Article and User before finishing. Now the Test itself is where it gets interesting:

describe('Method Save', function() {
	it('should be able to save without problems', function(done) {
		return article.save(function(err) {
			should.not.exist(err);
			done();
		});
	});

	it('should be able to show an error when try to save without title', function(done) {
		article.title = '';

		return article.save(function(err) {
			should.exist(err);
			done();
		});
	});
});

MeanJS is using should.js for the assertions, check out its perfect documentation to know which assertions can be made.
In these 2 tests we’re making sure the Article saves without an error, and in case the title is blank, that it gives an error.

To run the Mocha tests run the command grunt mochaTest.

Let’s move on to Frontend tests, with Karma framework. The tests on Karma are fairly similar to Mocha. Let’s have a look at public/modules/articles/tests/articles.client.controller.test.js

describe('ArticlesController', function() {
	// Initialize global variables
	var ArticlesController,
		scope,
		$httpBackend,
		$stateParams,
		$location;

	// The $resource service augments the response object with methods for updating and deleting the resource.
	// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
	// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
	// When the toEqualData matcher compares two objects, it takes only object properties into
	// account and ignores methods.
	beforeEach(function() {
		jasmine.addMatchers({
			toEqualData: function(util, customEqualityTesters) {
				return {
					compare: function(actual, expected) {
						return {
							pass: angular.equals(actual, expected)
						};
					}
				};
			}
		});
	});

	// Then we can start by loading the main application module
	beforeEach(module(ApplicationConfiguration.applicationModuleName));

	// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
	// This allows us to inject a service but then attach it to a variable
	// with the same name as the service.
	beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
		// Set a new global scope
		scope = $rootScope.$new();

		// Point global variables to injected services
		$stateParams = _$stateParams_;
		$httpBackend = _$httpBackend_;
		$location = _$location_;

		// Initialize the Articles controller.
		ArticlesController = $controller('ArticlesController', {
			$scope: scope
		});
	}));

	it('$scope.update() should update a valid article', inject(function(Articles) {
		// Define a sample article put data
		var sampleArticlePutData = new Articles({
			_id: '525cf20451979dea2c000001',
			title: 'An Article about MEAN',
			content: 'MEAN Rocks!'
		});

		// Mock article in scope
		scope.article = sampleArticlePutData;

		// Set PUT response
		$httpBackend.expectPUT(/articles\/([0-9a-fA-F]{24})$/).respond();

		// Run controller functionality
		scope.update();
		$httpBackend.flush();

		// Test URL location to new object
		expect($location.path()).toBe('/articles/' + sampleArticlePutData._id);
	}));

});

This is a bit more complex because of some AngularJS lingo (which is always a bit more complex). My tip for AngularJS: be patient, read the code slowly to fully understand it.

The first beforeEach function definition (after the var definitions) is there to add the toEqualData function (so we can compare objects properly). The second beforeEach is easy to understand.
The third one injects the extra variables needed, and uses underscores so that local vars can be named the same as the services (purely a convenience/readability thing).

After all this we get to the test itself (starting with it(, just like Mocha). Basically we’re checking the update functionality for Articles by assuming that after the PUT response & update the url is updated to the article’s page.

There’s a lot to learn about Mocha & Karma, and they are quite similar (though I found the Backend tests to be easier to follow, as AngularJS is not involved).

The next article will cover Yeoman generator, and the aspects of generating Models/Controllers/Views.

Tagged with: , , ,
Posted in Technology

Abmss & Spotpanda


Yep, it’s one of those weeks.
Sadly this week I wasn’t able to have enough time to continue my research on MeanJS.

So with that I highly recommend readers to give a listen to my interview with the co-founder of Spotpanda – lots of interesting insights.

Another interview, done this week by Alex, is with the co-founder of Abmss – a social coaching company.

Tagged with: , ,
Posted in Technology

Basics of MeanJS

The first thing I’ve noticed with MeanJS is the amazing Documentation.

For people familiar with the concepts of MVC (Model, View, Controller), the folder structure of MeanJS should be really easy to understand.

Models

Mongoose (built in) makes the part of Model building a lot easier, and very easy to read.

For people who are use to building the DB architecture first, then generating Models from it, I haven’t found a solution for that (and I think that because of the nature of MongoDB it’s a bit difficult working that way). I suggest starting to work from Models to DB instead.

The following Model is for an Article object, and is generated by MeanJS after install.

var ArticleSchema = new Schema({
	created: {
		type: Date,
		default: Date.now
	},
	title: {
		type: String,
		default: '',
		trim: true,
		required: 'Title cannot be blank'
	},
	content: {
		type: String,
		default: '',
		trim: true
	},
	user: {
		type: Schema.ObjectId,
		ref: 'User'
	}
});

mongoose.model('Article', ArticleSchema);

As you can see, the fields created, title, content, user are described here, each with its own type/default/error message/reference.

The types of fields (=SchemaTypes) that can be defined are

  • String
  • Number
  • Date
  • Buffer
  • Boolean
  • Mixed
  • ObjectId
  • Array

Mongoose has some good explanation about it here.

Notice that user is referencing another Model!
MongoDB doesn’t really have joins, but mongoose helps you to translate what you know and love from SQL to NoSQL by having these Model relationships (just like in other MVCs).

Controllers

For those who are familiar with Controllers in general, there’s not much new to introduce here.

Every Controller (that uses a Model) should require the Models you want to use:

var mongoose = require('mongoose'),
      Article = mongoose.model('Article');

(for articles.server.controller.js)

These are standard Express controllers, every Action in a Controller is a function inside the exports (in NodeJS that’s the object that’s returned when the controller is required), for example the Article/List action:

exports.list = function(req, res) {
	Article.find().sort('-created').populate('user', 'displayName').exec(function(err, articles) {
		if (err) {
			return res.send(400, {
				message: getErrorMessage(err)
			});
		} else {
			res.jsonp(articles);
		}
	});
};

As you can imagine, req & res are the request & response accordingly.

The first line describes a pretty straight forward query which fetches all Articles, sorted by creation date ascending.

The populate function helps “joining” (there aren’t real joins on MongoDB, so Mongoose gives us Population) the Users collection (MySQL->table MongoDB->collection) with the Article.

Afterwards we execute the query, check for errors and respond accordingly, otherwise return a JSON response (luckily MongoDB stores everything as JSON anyways, so this is incredibly fast).

Routes

Like in every MVC framework, routes define the different url routes that are used, and to which controller/action they go to. To better understand routes lets take a look at an example generated by MeanJS:

var users = require('../../app/controllers/users'),
	articles = require('../../app/controllers/articles');

module.exports = function(app) {
	// Article Routes
	app.route('/articles')
		.get(articles.list)
		.post(users.requiresLogin, articles.create);

	app.route('/articles/:articleId')
		.get(articles.read)
		.put(users.requiresLogin, articles.hasAuthorization, articles.update)
		.delete(users.requiresLogin, articles.hasAuthorization, articles.delete);

	// Finish by binding the article middleware
	app.param('articleId', articles.articleByID);
};

First we require the different controllers to which we’ll be routing (otherwise actions like articles.list won’t be defined).

As always we’re using modules.exports (in controller was simply referred to as exports, both should state the same in my opinion).

As you can probably gather, .get/.post/.put/.delete are HTTP methods.

Tests

I’m going to try and cover tests in the future, since there are frameworks both for Backend & Frontend testing, I’d like to cover this separately.

Backend Views

The views that are on the backend side are for errors pages (404, 500, etc.), and general layouts.

There’s a good explanation for why the developer decided to have some views basic views on the backend side.

The backend views use Swig templating engine, which reminds me of Django’s templating language (or many others). For the frontend views we’re using AngularJS’ templating (so no need to mix the two).

Debug / Inspect

Probably one of the most crucial things you’d like to do is inspecting the app.

node inspector is a great tool, that’s very similar to chrome’s web inspector, and let’s you inspect your application thoroughly.

make sure you have it installed

sudo npm install -g node-inspector

then simply instead of running grunt (that’s what you should execute when running the MeanJS app), run grunt debug and go to the following URL: http://localhost:1337/debug?port=5858

The ports are the default ones, which can be changes on gruntfile.js

Goodbye Backend, Hello Frontend!

I’m sure you’ve noticed that the controllers & models had .server in their filename. This to make a distinction between backend & frontend files, which can be harder to see with the MEAN. Frontend files have .client in their filename for the same reason.

On to the public/ folder!

Lib

Angular stuff, Bootstrap & jQuery, the base libraries. Nothing much to add.

Modules

Each Model has its own Module, remember we’re in AngularJS realm now.

Let’s look at articles/ which has

  • config -

    • articles.client.config.js – holds the configuration (duh!)  of the articles module, in this example we’re adding some menu items:

      angular.module('articles').run(['Menus',
      	function(Menus) {
      		// Set top bar menu items
      		Menus.addMenuItem('topbar', 'Articles', 'articles', 'dropdown', '/articles(/create)?');
      		Menus.addSubMenuItem('topbar', 'articles', 'List Articles', 'articles');
      		Menus.addSubMenuItem('topbar', 'articles', 'New Article', 'articles/create');
      	}
      ]);
      
    • articles.client.routes.js – configuring routing for the module, pay attention because here we’re talking about the routing for AngularJS, this means after the Hash sign (#), example: http://localhost:3000/#!/articles/create

  • controllers – loading the variables from the backend’s controller, making some form logic.

  • services – various services, for instance Authentication service for the users module (

  • tests – as mentioned above, tests will be covered in a separate article as I think they deserve one.

  • views – this is where the familiar AngularJS views go (with things like data-ng-repeat, data-ng-bind and so on).

I hope this clarifies a bit about the folder structure of MeanJS, it can definitely be overwhelming in the beginning but one has to understand that every tool has a purpose.

Even more important – not all tools will cost you in performance (as many of them are for the development stage like SASS), if anything the performance will be a lot better than in your LAMP stack.

Next article will cover the testing frameworks (unless I have a tough week, in which case something shorter :) ).

Tagged with: , , , , , ,
Posted in Technology

Check out Agronode

Check out Alex’s Interview on StartCast with Agronode’s founder – Andrija.

There are some very good insights as to bringing the Startup & IT world into agriculture.
I really liked this interview and recommend people to take a listen.

I’ll be back next week with the planned article (which had to be postponed due to chaos).

Tagged with: ,
Posted in Technology
Welcome to KidsIL
A blog for Technology, Brainstorming & Berlin!


Take a look at StartCast.
A podcast with the sole purpose of interviewing co-founders of Startups in Europe & around the world.


You should try Berlin On Feier, an App I built for finding the best parties in Berlin.