DEV Community

Cover image for Nodejs Best Practices(part 2a - Choice of Architecture/Design Patterns )
ADJARO LORD OGAGA
ADJARO LORD OGAGA

Posted on • Edited on

Nodejs Best Practices(part 2a - Choice of Architecture/Design Patterns )

This is me, four years later after my first Nodejs code, with a colleague saying, "so far it works, just leave it". I was like, seriously?
Alt Text

Appologies

My sincerest apologies for the long wait, the multi-tasking of been an active software Engineer and a tech writer is no joke. Trust me.

What we have covered

In the previous article we introduced Nodejs, ran some basic commands, created a server using koa.js. A server that returned just "Hello koa".

What we will Cover

Now let's take this further and choose how to structure our code. Here's the connection , designs are drawn by architects, hence the title ......Architecture/Design Patterns.
Disclaimer: This article will not meddle into the argument of which design pattern is better, trust me sometimes it takes me days and on one occasion weeks on deciding which design pattern to adopt for new applications I build. poor me!!
Well, according to my friend and colleague, truth is you can build an application using just a single file. But consider this; Will You build a house with just four walls?
Alt Text
Please lend me your imagination for a second and take a second look at the above house. The toilet, the kitchen, the living room, bedrooms all arranged in-between those four walls. How convenient that will be!! If you're thinking nahhhh you need more walls, demarcations and a clear distinction of which is which. I cant be doing my business and risk a visitor storming in.. You're right! To be sure four walls is a design pattern, but just a very bad one.
In Nodejs there are battle tested patterns, needless to say, a pattern must be tried and tested before it can even be called 'A DESIGN PATTERN'

Design Patterns In Nodejs

There are books and articles dedicated to this subject. I summarry though, we can rightly but arguably group design patterns in four containers, so to speak. They are:

  1. Creational
  2. Behavioral
  3. Structural etc. Hmmmmm. Those names already bore me to death.... Ok lets just pick. An Advice: If you are anything like me, I have my learning peak period, then I read technical jargons and master them. 😉 So take out time to do that.. Capishe?

Ok, Now choosing... I will go with a design somewhat similar to the factory design pattern. That was easy!! But trust me you'll have to really understand these design patterns, because truth is each is tailored to solving a particular kind o problem. And what problem are we solving here?? Nodejs Best Practices! So, just be sure next time you want to set up a project, no matter how small, choose a design pattern.
Ok.. Talk's over.. lets implement the factory design pattern in our code.
NEWS: We will be building a mini e-commerce api with nodejs, koa.js, and graphql. So, let see how to implement a FACTORY DESIGN PATTERN

Fun-Fact: Why I chose Factory?

I am a Mechanical Engineer By training. So I still have a little leaning towards anything that sounds like machines.. 😅 ..
Ok more seriously. Factory is under creational design paterns and in our system we will be ;

  1. CREATING USERS,
  2. DESTROYING USERS,
  3. CREATING ORDERS,
  4. CREATING NOTIFICATIONS. Yes!! Creating , Creating and destroying, so why not factory. There are other patterns that will work, but we have chosen right?

IMPLEMENTING FACTORY DESIGN PATTERN

Now at this point I must warn, Javascript is not java, ok, I know you know that, lol, but what I mean actually is; Javascript is not a purely object oriented language. But thanks to ES6, ES7, ES8 and of course TypeScript, now we can almost do everything in Javascript in an object oriented way..(typescript is not javascript, but take it as a father that was born after his son.. Please we stick to the course, gear the rudder back, this is not important for now ) ok...
So let revisit our small app from here with just an additional file .gitignore. You can add that or continue as same.
Alt Text
And our code was

import Koa from 'koa';
import mount from 'koa-mount';
import graphqlHTTP from 'koa-graphql';
const app = new Koa();

app.use(ctx => {
  ctx.body = 'Hello Koa';
});

  app.listen(8080, () => {
      console.log("Server running.......")
  });
Enter fullscreen mode Exit fullscreen mode

Now lets turn our house into a factory.. Cool!
We will introduce lots of stuffs...
In our factory we will have, machines that draws the templates. The template will be so robust that it contains instructions on how to create, destroy and even extend the design design. All automated! How cool!! Another machine will take that design and prototype it, and in fact it can create any number of items using that single template designed by the very first machine. Then there will be machines that create other stuffs as needed.
Our machines will be Javascript CLASSES!! Saw that coming or nah?
Ok, but first things first lets demarcate our app GRACEFULLY!! 😃
I will show you two ways I structure my apis for production apps, with a minor modification..
Fact: Two of my Nodejs api serving actual users run on the structures I will now show you below. So Yes! They are battle tested. Note at this point that, the design pattern you choose to go with, might affect how you structure your files... Leggo! oooops! I meant to say lets go.... lol

First Structure Style

While I will try my very best to reduce complexities, I can't but help to think that you will want a template for your next project... So there might creep in some kindaaa complexities, but trust me , you'll get the point...
Take a closer look at the file structure below

Image description
Intimidating???? Well have you ever seen a tree? lol! Stupid question. So what you see is like a tree, with branches.

Breaking Down

So we have the first layer as shown below
Image description
Then in the app folder there is where our app actually lies, I mean the logic
So in the app there are the src, helpers, config, assets and a server.mjs file as shown....
Image description
Digging further in the src folder we have modules and an indexd.mjs file, infact this is where all our code will live, see the structure below
Image description
Honestly to a beginner this looks like too much stress, well, you will know stress when you decide to go dumping everything anywhere anyhow, and say you end up having like a hundred files or more. Among the numerous benefits of structuring your file in a well defined manner is the maintenace clause and for me is the art. See coding is art, backend is beautiful can even be more beautiful than the ui designs , outrageous??? nahhh.. I don't think so.
Moving on...
Now to the part where we start building thinggggggggggs.... yeahhhhhhhhh! Ok.
Now in the modules , I created quite a number of modules, just so you have a feel of what a real life app can be, and how things can easily get out of hand should you not have a well defined structure.
Image description
A closer look in the users folder, you'd see a folder and three different files. Oboy!! we are building a house indeed...
Yes! Our factory is there and we are gonaa start the process... This is long enough. I need a break.
In Part 2b we will fill our factory complete the user process and also see how we can decouple things.
Happy Hacking!!!!!

Top comments (0)