Service and Controller Layers, Business Logic and Project Structure with Node.js - javascript

I come from a decade of experience with Java EE, SE and Java with Spring. If there's something that was drilled in me by myself and other fellow developers, was how to make use of design patterns, separation of responsibility, separating definition from implementation, interface segregation, etc. Also, we were always worried about testable code (unit testing and integration tests).
When I was learning Java, there wasn't a single book, magazine or website that didn't implemented things with those rules in mind, to the point of boredom. So we always new how things should be done from an architectural point of view when starting new stuff or maintaining code. With time, projects like Spring Boot and JBoss Seams started to give out of the box a basic project layout witch you simply followed to success(or at least you should...).
Now that I delve deep in Node.js, I miss that so much. There seems to be only a handful of people on the web worried about it and trying to teach newcomers how to write good backend code with Node.js.
People teach you how to boot express and put all of your code (database, logging, mailing, error handling and so on) inside an express route.
Of course, when I started learning Java, there was nothing preventing you from using Servlets directly with some JDBC code thrown inside, or even worse, Scriptlet inside JSPs...
I would appreciate so much to know how you for instance implement a service layer, where do you put your business logic? Do you put it in classes or functions that returns other functions? How to write easily testable code by Mocha for instance... Do I really need a controller layer, or can I trust my routes to cover that responsibility?
I'm interested in JavaScript only on the Backend, using Express.js, Socket.io, RabbitMQ, Passport.js, and GraphQL(in the future). Not interested in any rendering engine or template engines, much less JavaScript on the Browser. I'm already very proficient with Sequelizer and Mongoose.

I know the feeling of switching from Java Spring Boot to the Node.js stack. It was confusing for me in the beginning aswell, but with time you find your set of frameworks you like.
I'm probably not qualified enough to answer your entire question, but I can give you some advice of what framework helped me the most after starting with Node.js.
For me, this framework is NestJS.
It's a progressive Node.js framework to build scalable server-sided applications, based on Express.js. It supports a lot of different design patterns, but I personally use a pattern consisting of controllers, services, repositories and providers. You can use multiple different databases obviously.
Nest.js stands out for me, because you don't need any 3rd-party tutorial or documentation, because their own documentation is done really well and has basically all the information you'll ever need. It is really expandable with additional dependencies (most of them are in-house developed and have great documentation aswell).
What also has to be mentioned, is that as a Java-dev you will probably miss OOP if you switch to JavaScript. In Nest.js tough you only develop with TypeScript and overall it gives you a feeling very similar to Java Spring Boot.

Related

Asp.Net Core + Angularjs2, together or separately?

I will start to develop a new Project and i want use Asp .NET core and angular.js but i have a question what is the better way, use asp.net and angular together or separately?
I defined my architecture in this form
Cliente1(Angular)->RestApi->BussinessLogic->DataAccess->DB
yes, i see that my architecture says me that i need manage asp .NET and angular js separately, but I'd like to hear any suggestions.
UPDATE:
thank you for your answers, in the end both they have their pros and cons, i would like to share with you this articles:
Together: http://proudmonkey.azurewebsites.net/asp-net-core-getting-started-with-angularjs-2/
separately:
Part one: https://chsakell.com/2016/06/23/rest-apis-using-asp-net-core-and-entity-framework-core/
Part two: chsakell.com/2016/06/27/angular-2-crud-modals-animations-pagination-datetimepicker/
In general in programming you should separate your logic the most you can.
You will want to separate both projects for so many reasons :
You have a web app right now (angular) but maybe in a near futur you will need to have a mobile app (hybrid or native)
You can be more than one person working on the project, for example you will maybe need some designer/integrator to work on the app, and you dont want to share with him your back end, same applies if you have a back end guy.
two projects means maybe two source control repositories, means more control on branches, versions, rolling back ...
etc ...
I hope this can help.
If I see other benefits, ill update this answer.
Keep them separate, your MVC Part will be mainly REST APIs which has nothing to do with the JavaScript, HTML and CSS in the Angular Project, besides, if you want to build another client, EX: Mobile, then it will have its own project as well, this way you will have a clean structure for your solution.
So, you should have the following:
YourProject.REST
YourProject.Angular
YourProject.MobileClient
Also, the separation will make it easier for the teams working on the project, the one who will work on the front end doesn't have to worry about any other code not related to his tasks, the same for the developer working on the APIs, and each project can be structured as per the best practices for its technology.
You question is opinion based more than facts, so here is my opinion.
I have done few projects with ASP.Net MVC, Web API and AngularJS. They all stay in a single Web Application Project. Note: I have few class libraries for strongly typed Angular Helpers, Business Logic and Data Access.
Here are the advantages
I authenticate user using Owin Middleware, then redirect to Angular. The main advantage is I do not have to maintain Bearer Token or Authentication Cookie explicit inside Angular.
Second, I use csthml as strongly typed Angular view rather than plain html. It is the best of both world.
Last but not least, you can debug it easily rather than starting two projects at the same time, so that I can save resources on development machine. Everyone know Visual Studio is a memory hungry IDE.

JavaScript Web Application

I built a quiz taker app with Ruby on Rails, using the MVC framework. I want to do basically the same thing with pure JavaScript, and add more features with jQuery for mobile devices and special effects, since jQuery is just awesome like that.
I have looked around on sites like TodoMVC for comparisons on frameworks, but I'm foreign to how these frameworks function. Why do they use Collection rather than Controller in their MVC definition? It seems to me that these are just client-side frameworks. Would I use something like Backbone.js for client-side work and Node.js for server-side?
I'm just unsure as to how development with pure JavaScript functions. I need to create a database to store quiz and user information and be able to access that database when viewing most pages, so I feel the MVC framework is the best way to go.
Any suggestions as to where to start?
Wow, that's quite a broad post; let's take things one at a time
Why do they use Collection rather than Controller in their MVC definition?
The exact answer varies by library, but a simplistic answer is that the Controllers in most Javascript apps doesn't really need any framework; they can be raw Javascript and work just fine as they're usually not very complex.
Furthermore, parts what you might consider to be "the Controller" are often provided separately. The primary example of this is Backbone's Router object: it is similar to the implied routing (and routes.rb) in Rails, or the urls.py in Django. Just as those frameworks don't consider routing to be part of "the Controller", Backbone (and similar frameworks) provide routing as a separate piece ... even though it could fall under the C in MVC.
Similarly, much of the DOM manipulation functionality that jQuery provides would normally belong in the Controller of an MVC app, so in a sense jQuery helps you build your controllers; it's just not explicit the way Backbone.Model helps you build your models.
Would I use something like Backbone.js for client-side work and Node.js for server-side?
That's really apples and oranges; to put in server-side terms, Backbone is more like Rails, and Node is more like Ruby (or Mongrel or something). So yeah one's client-side and the other's server-side, but the differences are deeper than that.
Any suggestions as to where to start?
Pick a framework and get your hands dirty! Seriously, you can spend hours reading reviews of the different frameworks, and still be no closer to making a decision at the end than when you started (I speak from experience). But if you just pick one and try it, you'll likely find that it either "gels" with you or doesn't pretty fast.
Personally, I'd recommend starting with Backbone just because A) it's very popular these days, and B) I'm biased: I use it on a daily basis and love it. Also, it probably would fit you well because it was created by the CoffeeScript guy (and CoffeeScript was his attempt to make Javascript more Ruby-like). However, Ember.js is also very popular these days, and Hector mentioned ExpressJS, which I know nothing about but could be cool.
But the point is, pick one, do a hello world, or maybe something a little more complex like an introductory tutorial (Backbone has one around a To Do app). A few hours of coding with it will tell you far more than I (or anyone else on Stack Overflow) ever could about whether it's right for you.
If you are looking for a JavaScript MVC-like framework take a look at Express.js http://expressjs.com
Express.js is more like Sinatra than Rails, but it will give you a good foundation on the server side.
I would definitely look at Google Closure. I have started to use it with LimeJs on a personnal pet project and really got caught with it's compiler and it's modular design.
It's not really MVC, but since JavaScript should be thought more in an asynchronous fashion, I tend to think more of it as event driven than simply a request-pipeline-response way.
So, Closure Library and jQuery / jQuery UI (both on Google API) for the client side and ExpressJs for the server side. Also, take a look at this framework comparison chart, you might find it interesting.

Javascript coding guide with test driven development

I'm migrating from server side development (java, php) to client side - HTML, CSS, javascript.
Though I technically understand (mostly) how javascript works, I have not found a good guide to creating an application - particularly with regards to how to organise functions and objects and setting up a solid test framework for them.
I'm currently half way through the Ruby on Rails tutorial
http://ruby.railstutorial.org/
which is excellent - I now feel confident in understanding the standard structure for arranging all the code in an application, and setup good testing practices as I go.
Plus, the integration with heroku and git make for a really tangible real world example, making for a complete understanding of how to develop and deploy a rails app.
Can anyone recommend a similar kind of guide for JS/AJAX development?
One good way to write JavaScript is to do it in a modular fashion. For dependency loading, you would also need module loaders like RequireJS. As for structure, there are a lots of frameworks out there, I suggest you give BackboneJS a try. You would also want to make your JS scalable so that you won't ever have to worry about expanding. Here's more videos about it as well.
There are a lot of frameworks to choose in JS. Test them all out and create a stack which you feel comfortable playing with.
I don't think you'll find a similar tutorial as on Ruby on Rails about Javascript, because Rails is a framework and Javascript is just a language that has hundreds of different frameworks built around it. I don't know what kind of applications are you willing to develop, but Backbone.js is an MVC framework for frontend development and you could search some tutorials on it.
However, if you're just starting out with JS, you probably want to learn first on the basics of JS. Good source for that is for ex. MDN JS guide:
https://developer.mozilla.org/en/JavaScript/Guide
Then you might want to check out guide on JS design patterns for learning how to structure your code:
http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#designpatternsjavascript
Hope these will help!

Backbone-based web app for rails backend: separate project or on top of rails?

I currently have a web app written in rails3. I want to write a backbone-based js app that will consume the rails3 services; while there are alot of examples of backbone with rails, I would prefer to build it in a different project. This project would be pure html+css+js, wich would then point to the other proj's services.
What are the advantages or roadblocks of this approach?
Are there any other approaches?
I've noticed that most of the rails3-backbone projs on github do alot of the magic behind the scenes (ex: precompiling handlebar assets, auto-including js files), which makes it more difficult to understand how all the pieces work together. Also, if I want to package an app using phonegap/trigger.io/etc, wouldn't this be more difficult?
When it comes to writing Backbone application, it actually makes a lot of sense to develop it solely on its own. In other words, develop it, as you said, as a pure html+css+js application.
There are very good reasons to do so:
Deployment
Consider when you are deploying your application. At some point you will surely want to deploy some modular component of your application. This maybe the backend services which are responsible for serving json to your clients, or it could be a tweak on the UI. Whichever it may be, it is best if you are able to deploy each of them independently.
Modularity
It may sound attractive to be able to use some rails magic behind the scenes to help develop your UI. However, consider the modularity of your project.
IMO, Backbone (or any AJAX application) is beautiful. And the beauty comes from the very fact that the UI code really has nothing to do with the implementation of your backend. It could talk to a PHP/JAVA/RAILS/PYTHON/YOU-NAME-IT server, and it still wouldn't matter. That is, if you're implementing a RESTFUL server. In fact, the UI code could rest on an NGINX server that serves nothing but static content, and it would still run perfectly fine. This is actually what you want. Your UI code should at no point (during development or production) be aware of your backend's framework or whatever tools your backend supports. It would be a crime to introduce unnecessary dependencies into your Backbone project.
Imagine one day when you see fit to migrate to a different architecture which isn't Rails. It would be a nightmare if there are any dependencies at all. Much rather have a UI that is totally independent of your backend implementation.
Packaging
You mentioned you're going to use PhoneGap to package your application. This is probably the biggest reason why your project should be independent. You will not have the luxury of loading your js from your servers when you're say, submitting your app to Apple, if you ever plan to do that. All scripts must be packaged into the App which must be standalone.
Last but not least, to answer your question about suggestions for 'other approaches'. That is quite vague, so I'm not sure if this suggestion would help, but I wanted to point you to some resources that would help organize your Backbone projects, and make your life easier.
Backbone with RequireJS
I would argue that this is the most wonderful way to work with Backbone. RequireJS let's you specify your dependencies in your js files much like you would import in compiled languages, which helps a lot when it comes to organizing your Backbone project, and breaking the code down into smaller modules. The optimization tool that requireJS provides also let's you compress all of your javascript file into a single file. I believe that will come in handy if you want to package your project in PhoneGap.
Underscore
You mentioned using HandleBar. However, I recommend that you look into underscore's templating engine which is inspired by RoR's templates. And assuming that you're quite comfortable using Rails, the underscore templating engine might just be what you're looking for.

Is Node.js a good alternative to build complete websites?

I'm wondering if using Node.js (express.js) is the best option to go for a complete website. I've been using Rails + Node.js and am wondering if this is still the best option or if I should move completely to Node.js.
Are there websites built completely with node.js? I imagine it must lack many things Rails offers.
I imagine it must lack many things
Rails offers.
I gave a short list below but I would like to know what you could be missing and I think(almost certain) we can give you some alternatives on node.js.
Modules
node.js is getting pretty complete and I think you can run your entire site using only node.js using for example the following modules. I assume you know about npm. If not I really advice you to google for it and learn that. To search npm you can use http://search.npmjs.org:
web framework:
High performance, high class web
development for Node.js
https://github.com/visionmedia/express
Socket.IO aims to make realtime apps possible in every browser and mobile
device, blurring the differences
between the different transport
mechanisms.
https://github.com/learnboost/socket.io-node
I believe with these two web-frameworks you can create a lot of sites. For example express is a very powerfull web framework and supports a lot of cool things like:
session support.
a lot powerful template engines. I like Jade for example. You could also share these between client and server a lot of the times easily.
excellent routing.
just to name a few.
database:
Redis is an open source, advanced
key-value store. It is often referred
to as a data structure server since
keys can contain strings, hashes,
lists, sets and sorted sets.
https://github.com/mranney/node_redis
MongoDB (from "humongous") is a scalable, high-performance, open source,
document-oriented database.
Mongoose is a MongoDB object modeling tool designed to work in an
asychronous environment.
https://github.com/learnboost/mongoose/
With those two databases I think you should be able to accomplish most of your tasks. The nice thing is that Redis is extremely fast/simple advanced KV-store(dataset in memory/also supports VM) and supports replication while Mongodb is more completely(slower then redis) and also supports sharding.
authentication:
Authentication and authorization (password, facebook, & more) for your node.js Connect and Express apps.
https://github.com/bnoguchi/everyauth
Like I said previously you can get a long way with only these modules.
Express.js is more akin to Sinatra. They're simpler frameworks than rails.
Express's list of sites is fairly small http://expressjs.com/applications.html
So I think it's also good to look at Sinatra's list http://www.sinatrarb.com/wild.html
So to answer your questions in reverse order. Yes it lacks all the features of rails. Yes there are sites written completely in Express. And going to 100% Node.js might be the right decision for your site.
It depends on which features you'd miss and what performance you need.
I'm not sure, but I guess it's perfectly possible. I have built complete sites using plain server side javascript for years without problems. The advantage of node.js seems to be its event driven model and things like socket.io. I just started experimenting with it, I'll probably will try porting an existing site to node.js.
Here you can find a large list of sites built with node.js.
Finally, you may want to read: What it’s like building a real website in Node.js
Yes, as of now node.js lacks many (well, at least a few) things rails offers. Eventually the set of available node.js modules will collectively provide good alternatives to RoR across the board. Or at least different (and often more modern) approaches to the same fundamental problems. There are still some important things missing in the node.js ecosystem including a good ORM for postgresql (rails has ActiveRecord which is great) and a good DB schema management subsystem. Both of these do not exist in the node.js ecosystem as of this moment, but surely they will be there in due time. Rails has these down pat right now.
There are some tricks node.js has that RoR doesn't. Debugging in node.js is more seamless than RoR and express.js is more flexible. Express is the library approach (you tell it what to do) whereas rails is the framework approach (you fill out the boilerplate it creates for you). There are also some fantastic things like stylus and jade, which have equivalents in rails, but when you have a full app written in one language (either javascript or CoffeeScript, which I prefer) and everything is in a modern node.js/TJ Holowaychuck style, you get a level of cohesiveness that is really nice to work within.
The other thing to keep in mind is that while the list of available node.js modules is quite impressive, many of them are not as mature and battle-tested as their rails/django analogs. It's hit or miss, so beware.

Categories