DEV Community

Cover image for Getting Started with Grandjs
tareksalem
tareksalem

Posted on

Getting Started with Grandjs

Hi,
I came back again :D

I have introduced grandjs three weeks ago, you can find the introduction to grandjs here

Today is the getting started tutorial to jump in Grandjs and start working with this amazing node js framework.

What do you need before starting with grandjs ?

You need to know the following:

  • Javascript basics
  • Nodejs fundamentals
  • Javascript OOP and ES6 classes

Grandjs Getting Started

Install Grandjs

to install grandjs you don't need anything just you need to be installed nodejs on your machine so you can install grandjs from NPM by writing the following command:

npm i --save grandjs

Yes, you now got grandjs installed.
Now it's time to understand how does grandjs works

What are the packages installed with grandjs ?

Grandjs installed with some packages to facilitate the process.
one of these packages is handlebars template engine for server-side rendering HTML and data binding.
the second package that Grand js uses is a multiparty library for file uploading and request body parsing.

Setup Grandjs configuration

After installing Grandjs, you need to set up its configuration to start the app, the configuration of it is pretty simple and easy, you just need to call setConfig function as the following:

const Grandjs = require("grandjs");
Grandjs.setConfig({})

this function takes one parameter as an object, this parameter has som props, one of them is mandatory which is the port of the app that will run on, and also the ENCRYPTION_KEY to use in hashing and encrypting methods

Grandjs.setConfig({
    //define the port
    port: process.env.PORT || 3000,
    // http is optional you can specify http or https, if you don't specify Grandjs automatically require HTTP module
    // http: http,
    // if you specified https so you should ssl files in this object
    // httpsMode: {
    //     key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
    //     cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
    // },
    // define the static files container folder
    staticFolder: "public",
    //enable the session
    session: true,
    //set the encryption key, Grandjs uses encription key to cypher info
    ENCRYPTION_KEY: "ncryptiontestforencryptionproces",
    // set the max age of cookies when you set the session of logged in users
    setCookie: {
        expires: {
            days: 20,
            minutes: 30
        }
    },

    //set it true to see the console info while development process
    logger: true,

    //set error page for global error pages
    errorPage(req, res) {
        res.end("error page");
    }
});

Now we sat the grand js configuration, so what we need is just calling another function to start the server, this function called initServer
as the following:

Grandjs.initServer();

Now Grand js started the server and also consumes the configuration we sat, but we still don't have any routes!

Routing System in Grand js

Grand js has a built-in router class that is used to build your routes based on Javascript ES6 classes, so Grandjs helps you to organize your routes and put every group of routes together with global and private middlewares

Write Router class in Grand js

Grand js has built-in router class you can extend it to build your own router, to do that you need to create a folder called routes or any name you want and create a file called router.js as the following:

const Grand = require("grandjs");


// define router class
class MainRoutes extends Grand.Router{
    constructor(options) {
        super(options);
    }
}

if you can see, I am extending the router class and call the super function into the constructor to inherit from the router class, and pass options as a parameter of the constructor, this options is an object has a property called base this property indicates the url of this class

const mainRoutes = new MainRoutes({base: "/"});

each router class has 4 main arrays you can define to start add routes to this class, these arrays imply the following:

  • getRouters (to put routes with Get method in it)
  • postRouters (to put routes with POST method in it)
  • patchRouters (to put routes with PATCH method in it)
  • putRouters (to add routes with PUT method in it)
  • deleteRouters (to add routes with DELETE method in it)
class MainRoutes extends Grand.Router{
    constructor(options) {
        super(options);
        this.getRouters = [];
        this.postRouters = [];
        this.putRouters = [];
        this.patchRouters = [];
        this.deleteRouters = [];
    }
}

We here extended the router but we still not specifying any route, so we will add a method to the class as a router, like the following:

class MainRoutes extends Grand.Router{
    constructor(options) {
        super(options);
        this.getRouters = [this.getHome()];
        this.postRouters = [];
        this.putRouters = [];
        this.patchRouters = [];
        this.deleteRouters = [];
    }
    getHome() {
        return {
            url: "/",
            method: "GET",
            handler: (req, res) => {
                res.render({
                    container: "views",
                    layout: "/layouts/layout.hbs",
                    body: "/pages/home.hbs"
                })
            }
        }
    }
}

This router class can have many methods, some of these methods can be routes so to the method as a route you need to return an object from this method has the following methods:

{
      url: "/", //the url 
      method: "GET", // the method of the request
      handler: (req, res) => { // the handler function of this request
          res.render({
             container: "views",
             layout: "/layouts/layout.hbs",
             body: "/pages/home.hbs"
          })
      }
}

and then add this method inside the proper routers array of the router class, so if this method implies a request with GET method so you should add this method in getRouters array as the following:

this.getRouters = [this.getHome()];

each router class you extend you can customize it as you want, you also can set an error router to it to be called once the required url is not registered, in the next tutorial we will learn how to add middlewares to the routes in Grand js.
Don't hesitate to ask any question, also please give me your opinion in the comments about this framework, see you next time,
thank you.

Top comments (0)