Generate Node App With Express

Hardeep Singh
4 min readFeb 25, 2018

--

Stay-Connected

To make Node app with express framework,
many things are needed i.e -

  • Environment where the server is made.
  • Generic Responses are set, in which form their is need.
  • Generic Routing need to be set.
  • Logging where their is a need and many more.

Now I would suggest for module - Express App Generator

So, what this Module Provide to us -

  • An Environment where server is Run on Any Particular Port.
  • Generic Router with unlimited Middle-wares can be set.
  • Give Generic Response as Data ,Items etc.
  • Obviously a Logger which helps to Log things.

Installation -

npm install express-app-generator --save

The generated app Provide us some default express Features like -

bodyParser.json();
bodyParser.urlencoded({extended: true});
bodyParser({ limit: ‘50mb’, keepExtensions: true });
(’view engine’, ‘ejs’); //for dynamic views
  • express static path `public` folder in root of app folder
  • if port is null it use default port `3000`

Generate Express App

let appGenrator=require(‘express-app-generator’);
appGenrator.generate(3789, function(err,app){
if(err){
return console.log(err);
}
// your express app is Ready to use
//you can check this on http://localhost:3789
console.log(app)
});

N O T E -
If you want to change express properties
you can change it by update `app.use()` or `app.set()`;

Routing

Their are Some Required things to be followed -

  • The `api` folder in root of app is must and in this folder all the .js files will be like `users.js` not `user.js` , `employees.js` not `employee.js`
    which means `s` or `es` sufix is must.
  • The `logs` folder is required ,this folder is use for
    logging the logs in JSON files ,which we get as in console.

What this Module Provides in routing ?

This Router Provides Simple CRUD Mechanism. In which Combinations of Arrays and Objects (telling you at down) are use To Build it.`appRouter();` method which is present in app generator helps to make Routing in Flexible way.

Lets get started for Routing -

//REST or CRUD
let api= app.appRouter;
//app is Express genrated app (above define how to get it)
api.model(‘users’)
.register(‘REST’, [ authentication ]); //REST or CRUD

N O T E -
This will make URL as http://localhost:3789/api/users .

We can use `REST` or `CRUD` Keyword to -`get`,`create`,`update`,`delete`,`get,search` these methods ready to use but for this, you must have all these methods present in `/api/users.js` file .

The array which is present just after the `REST` is use for middle-wares.
Suppose, I want to make authentication every time so the function of
authentication will be pass in the middle-ware Array.

Things `REST` Or `CRUD` Gives - (in api/users.js file)

  • If the Request is for POST then it go for -
exports.create=(req,res)=>{};
  • If the Request is for GET then it go for -
exports.get=(req,res)=>{};
// http://localhost:3789/api/users/:id

- If the Request is for GET (ALL) then it go for -

exports.search=(req,res)=>{};
// http://localhost:3789/api/users Here many query params ? can use.
  • If the Request is for PUT then it go for -
exports.update=(req,res)=>{};
  • If the Request is for DELETE then it go for -
exports.delete=(req,res)=>{};

N O T E -
All the the Middle-ware functions must have parameters `(req ,res ,next)` where
req,res are request response express generated objects and next is the
callback function which will call when one middleware work is DONE and
it will go to next middle-ware function (if present) in that array and perform same, then go the main function in the `users.js`.

Now I know how to make all middle-wares with one main function ( with REST or CRUD ).
This module also provide us to set in Routing in Manual Way -

  • In register `action` and `method` is Requied.
  • fiter for One Middleware and filters for Multiples.
  • For Single Request -
api.model(‘users’)
.register({
action: ‘GET’,
method: ‘get’, // method must present inside users.js
url: ‘/:id’,
filters: [authentication] //middlewares
});

// URL will be -
// http://localhost:3789/api/users/:id
  • For Multiple Requests -
api.model(‘users’)
.register([
{
action: ‘POST’,
method: ‘create’
},
{
action: ‘POST’,
method: ‘createWithProfile’,
url: ‘/withProfile’,
filter: authentication
},
{
action: ‘POST’,
method: ‘importer’,
url: ‘/importer’,
filter: authentication
},
{
action: ‘POST’,
method: ‘createWhenSignIn’,
filter: authentication
},
{
action: ‘PUT’,
method: ‘update’,
url: ‘/:id’,
filters: [authentication, groupCode]
},
{
action: ‘GET’,
method: ‘get’,
url: ‘/:id’,
filters: [authentication, groupCode]
},
{
action: ‘GET’,
method: ‘search’,
filters: [authentication, groupCode]
},
{
action: ‘GET’,
method: ‘searchInGroup’,
url: ‘/from/group’,
filters: [authentication, groupCode]
},
{
action: ‘GET’,
method: ‘getLeader’,
url: ‘/get/leader/:id’,
filters: [authentication, groupCode]
}
]);

N OT E-
`api` keyword in URL is Constant all over the Router.
So, your base url will be http://localhost:3789/api/ .

Responses

Here are Four Types of Responses — All the Responses are of status
Code is 200 .

DATA

  • It can take one or two params `data,message`, `data` is mandatory.
  • It is use as -
res.data({
name:”Leo”,
age:21
});

//res which you get from any query
  • This will give Response -
{
“isSuccess”:true,
“data”:{
name:”Leo”,
age:21
}
}

PAGE

  • It can take one or two params `items, pageSize, pageNo, totalRecordsCount`.
  • `items` is mandatory.
  • Can also use for Paginations.
  • It is use as -
res.page([
{
name:”Leo”,
age:21
},{
name:”Hardy”,
age:22
}
]);

//res which you get from any query
  • This will give Response -
{
“isSuccess”:true,
“items”:[
{
“name”:”Leo”,
“age”:21
},{
“name”:”Hardy”,
“age”:22
}
],
pageSize:2
}

SUCCESS

  • It can takes one params `message`, it is mandatory.
  • Can Use for Sending Successful Signature message.
  • It is use as -
res.success(`user successfully deleted`);
  • This will give Response -
{
“isSuccess”:true,
“message”:”user successfully deleted”
}

FAILURE

  • It can takes two params `error, message`
    `error` it is mandatory.
  • Can Use for Sending Error Signature message.
  • It is use as -
res.failure(`user Hardy already present`);
  • This will give Response -
{
“isSuccess”:false,
“message”:”user Hardy already present”
}

Hope you like it.

Stay Connected ;)

--

--

Hardeep Singh
Hardeep Singh

Written by Hardeep Singh

Founder and C.E.O at XpRate.com | Helping world to Grow 🌱

No responses yet