Structure Node.js App -  Fractal Pattern - 2019

Structure Node.js App -  Fractal Pattern - 2019

This article about structuring the backend for REST API’s which can be extend to graphql.

Originally published by  DEEPAK GUPTA at overflowjs.com

Note: The article give an overview of structuring and here is the code base for detailed understanding.

After working with many backend projects, i realised 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.

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.

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

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

10. 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

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.

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

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

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.

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.



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

3. Most of the times actions folder will have same the same structuring as the routes 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.

Note: Actions can call other actions too.

4. So, middlewares, utils, helpers, tasks will follow the same way ofstructuring 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


Originally published by  DEEPAK GUPTA at overflowjs.com

=============================

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow me on Facebook | Twitter

Learn More

☞ NestJS Zero to Hero - Modern TypeScript Back-end Development

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

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

☞ 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

node-js javascript web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Node.JS Developers | Skenix Infotech

We are providing robust Node.JS Development Services with expert Node.js Developers. Get affordable Node.JS Web Development services from Skenix Infotech.

How to Hire Node.js Developers And How Much Does It Cost?

A Guide to Hire Node.js Developers who can help you create fast and efficient web applications. Also, know how much does it cost to hire Node.js Developers.

Top Node.js Development Companies and Expert NodeJS Developers

A thoroughly researched list of top NodeJS development companies with ratings & reviews to help hire the best Node.JS developers who provide development services and solutions across the world. List of Leading Node.js development Service Providers...

Hire Web Developer

Looking for an attractive & user-friendly web developer? HourlyDeveloper.io, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...

Top Vue.js Developers in USA

Vue.js is an extensively popular JavaScript framework with which you can create powerful as well as interactive interfaces. Vue.js is the best framework when it comes to building a single web and mobile apps.