Fractal — Nodejs app structure 😃

Fractal — Nodejs app structure 😃

😃 Fractal — Nodejs app structure: This article about structuring the backend for REST API’s which can be extend to GraphQL 😃

😃 Fractal — Nodejs app structure: This article about structuring the backend for REST API’s which can be extend to GraphQL 😃

Note: The article give an overview of structuring and here is the code base for detailed understanding.
After working with many backend projects, i realized that structuring the app is equally important as the choice of tech stack and fractal app structure is always my choice.

Fractal pattern convey that similar patterns recur progressively and the same thought process is applied to the structuring of codebase i.e All units repeat themselves.

Note: To code a fractal pattern and see it visually, check here and don’t forget to follow me on Github.
Now, lets start with the crux,

App Root Structure

The root folder always remain same in any case of API’s structuring.

So, At root level we have -:

1**. app** is where our main app code goes and will discus in depth under app structure below.

2**. docs**(optional) is for documentation purpose.

3**. lib**(optional) is where the complied app code goes which is used for production env.

4**. migrations** is where all the table schema. I personally use knex.js and an self made ORM name tabel written on top of it.

Some of migration files (They are automatically generate from CLI)

5**. node_modules** you already know it 😃.

6**. tests **is where we write all our unit test.

The structuring of tests folder is like the actions or routes under app folder and will be explained in app structure section.

7**. config and config.sample.js **are where all of our configuration related to database, authentication, external api keys etc are stored.

If you are wondering why we have two such files, then **config.sample.js **goes to your repository so that other developer can know the file shape and can use to form their local config.js file.

Also, we can also have a config.production for production environment.

Note: config can be a separate folder too, that can have separate sub configs files for database, external Api’s key etc but it feel overkill to me.

  1. eslintrc is where the lint logic goes. Read more here.

  2. **migrate **is the file that pass our configuration from config.js to ORM and help us run migration from CLI, check the code here.

  3. **gitignore **is where we path to folder or filename that we don’t want to push on repository.

**11. package.json **— you already know it 😃.

Note: We will discuss only the app folder structure because other are straight forward. If you need any help or want to understand anything in code base then hit me up.##

The app Structure

app folder

1.** server.js** is the file that start your server and will have all middleware that is required for request parsing like bodyparser, cors, multer and errorhandlers etc and finally we add routes middleware.

Sample code for server.js

2.** routes** will have sub-files or sub-folders made as per the entities in project.

routes folder

The index.js under routes looks like as shown below. It have request handler middlewares and a catch all route.

index.js under routes

Note: We can abstract a big entity like teams in a folder and can call it as teams which can then have sub subfolder like members, contacts, dashboard etc. under routes.

Fractal pattern structuring in routes

A file under routes is where all request handler or sub-routes are written and the only purpose of them is to either call the action that is responsible for that route or the sub-route folder.

auth.js under routes

Note: **signup, login, logout, refresh and forgetpassword **in above image all are actions that are defined under action folder.

  1. Most of the times **actions folder **will have same the same structuring as the routes folder.

actions folder

Each file in **actions is for **business logic i.e all code that store, get, change real entities either in database tables or doing queuing function like enqueue and dequeue etc all happen here.

Sample code for auth file for signup action

Note: Actions can call other actions too.
4.** So, middlewares, utils, helpers, tasks will follow the same way of **structuring as action or routes do i.e main entity will act as a root folder and then will can have subfolder as per sub-entities and repeat.

5.** tasks.js** is used for running tasks from CLI created under task folder like database seed, clean database etc.

6.** nsqd**(optional) is use case specific for distributed messaging.

Note: NSQ is one the best i have used for distributed messaging it works great with no pain in production.
utils and helpers can be merged if need, i love to keep them separate so that i can reuse utils as its more generic in all projects

Why fractal
  1. Gives us phenomenal scale.
  2. Easy to debug as everything go with the domain logic flow.
  3. Easy to onboard a new developer to this codebase.

In Case of GraphQL we can get rid of routes folder. Few month back i tried using this structure with *GraphQL *check here (a raw sample)

If you are totally new to Node.js and want to make a backend for REST API’s then use this. It contains everything you need from setup to authentication already done for you, just run the shell script.

Note: I personally use our own self created ORM called tabel which we have used in production for many years and i promise you will love it. This ORM and this app structure is all you need for making any kind of backend with REST API/GraphQL.

It is (and will always be) a work in progress on fractal pattern, i was recently working on removing the entire routes folder and exposing action directly to **UI **so that the UI can directly call the function with the required parameter which is what *GraphQL *do but with REST API’s.

Fractal allows you to:

  • Reason about location of files
  • Manage and create complex domain entities with ease
  • Iterate quickly and scale repeatably

Special thanks to Kapil Verma who is creator of fractal pattern.

Top 7 Most Popular Node.js Frameworks You Should Know

Top 7 Most Popular Node.js Frameworks You Should Know

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser. In this post, you'll see top 7 of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser.

One of the main advantages of Node is that it enables developers to use JavaScript on both the front-end and the back-end of an application. This not only makes the source code of any app cleaner and more consistent, but it significantly speeds up app development too, as developers only need to use one language.

Node is fast, scalable, and easy to get started with. Its default package manager is npm, which means it also sports the largest ecosystem of open-source libraries. Node is used by companies such as NASA, Uber, Netflix, and Walmart.

But Node doesn't come alone. It comes with a plethora of frameworks. A Node framework can be pictured as the external scaffolding that you can build your app in. These frameworks are built on top of Node and extend the technology's functionality, mostly by making apps easier to prototype and develop, while also making them faster and more scalable.

Below are 7of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Express

With over 43,000 GitHub stars, Express is the most popular Node framework. It brands itself as a fast, unopinionated, and minimalist framework. Express acts as middleware: it helps set up and configure routes to send and receive requests between the front-end and the database of an app.

Express provides lightweight, powerful tools for HTTP servers. It's a great framework for single-page apps, websites, hybrids, or public HTTP APIs. It supports over fourteen different template engines, so developers aren't forced into any specific ORM.

Meteor

Meteor is a full-stack JavaScript platform. It allows developers to build real-time web apps, i.e. apps where code changes are pushed to all browsers and devices in real-time. Additionally, servers send data over the wire, instead of HTML. The client renders the data.

The project has over 41,000 GitHub stars and is built to power large projects. Meteor is used by companies such as Mazda, Honeywell, Qualcomm, and IKEA. It has excellent documentation and a strong community behind it.

Koa

Koa is built by the same team that built Express. It uses ES6 methods that allow developers to work without callbacks. Developers also have more control over error-handling. Koa has no middleware within its core, which means that developers have more control over configuration, but which means that traditional Node middleware (e.g. req, res, next) won't work with Koa.

Koa already has over 26,000 GitHub stars. The Express developers built Koa because they wanted a lighter framework that was more expressive and more robust than Express. You can find out more about the differences between Koa and Express here.

Sails

Sails is a real-time, MVC framework for Node that's built on Express. It supports auto-generated REST APIs and comes with an easy WebSocket integration.

The project has over 20,000 stars on GitHub and is compatible with almost all databases (MySQL, MongoDB, PostgreSQL, Redis). It's also compatible with most front-end technologies (Angular, iOS, Android, React, and even Windows Phone).

Nest

Nest has over 15,000 GitHub stars. It uses progressive JavaScript and is built with TypeScript, which means it comes with strong typing. It combines elements of object-oriented programming, functional programming, and functional reactive programming.

Nest is packaged in such a way it serves as a complete development kit for writing enterprise-level apps. The framework uses Express, but is compatible with a wide range of other libraries.

LoopBack

LoopBack is a framework that allows developers to quickly create REST APIs. It has an easy-to-use CLI wizard and allows developers to create models either on their schema or dynamically. It also has a built-in API explorer.

LoopBack has over 12,000 GitHub stars and is used by companies such as GoDaddy, Symantec, and the Bank of America. It's compatible with many REST services and a wide variety of databases (MongoDB, Oracle, MySQL, PostgreSQL).

Hapi

Similar to Express, hapi serves data by intermediating between server-side and client-side. As such, it's can serve as a substitute for Express. Hapi allows developers to focus on writing reusable app logic in a modular and prescriptive fashion.

The project has over 11,000 GitHub stars. It has built-in support for input validation, caching, authentication, and more. Hapi was originally developed to handle all of Walmart's mobile traffic during Black Friday.

Difference between AngularJS, React, Ember, Backbone, and Node.js.

The most common thing between all of them is that they are Single Page Apps. The SPA is a single page where much of the information remains the same and only some piece of data gets modified when you click on other categories/option.

Node.js Tutorial for Beginners | Node.js Crash Course | Node.js Certification Training

This courseis designed for professionals who aspire to be application developers and gain expertise in building real-time, highly-scalable applications in Node.js. The following professionals can go for this course :

Why learn Node.js?

Node.js uses JavaScript - a language known to millions of developers worldwide - thus giving it a much lower learning curve even for complete beginners. Using Node.js you can build simple Command Line programs or complex enterprise level web applications with equal ease. Node.js is an event-driven, server-side, asynchronous development platform with lightning speed execution. Node.js helps you to code the most complex functionalities in just a few lines of code...

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

The Complete Node.js Developer Course (3rd Edition)

Angular & NodeJS - The MEAN Stack Guide

NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

Docker for Node.js Projects From a Docker Captain

Intro To MySQL With Node.js - Learn To Use MySQL with Node!

Node.js Absolute Beginners Guide - Learn Node From Scratch

React Node FullStack - Social Network from Scratch to Deploy

Selenium WebDriver - JavaScript nodeJS webdriver IO & more!

Complete Next.js with React & Node - Beautiful Portfolio App

Build a Blockchain & Cryptocurrency | Full-Stack Edition