rest-creds

0.3.5 • Public • Published

REST-CREDS


A fast building and easy to use backend framework for NodeJs in ECMA 6. The module rest-creds encapsulates different technologies that are commonly used together to build a solid backend for applications, technologies as express(endpoints), json-web-token(protected endpoints), sequelize(orm) and others.

Be my patron :), so I can buy beer to enhance my development.

Getting started

This module requires the latest version of NodeJs that supports async/await keywords for promises.

To install the node module run the command :

npm install rest-creds --save

It requires the next folder structure in your project:

 - controller/
	 - *controllers here*

 - domain/
	 - *domains here*

 - repository/
	 - *repositories here*

 - model/
	 - *models(database tables) here*

 - injection
     - *dependency injection here* // soon more documentation.

 - database
       - *bd.sqlite -- Only if database dialect is sqlite*

 - index.js 

In index.js file the next code:

const { runBackend } = require('rest-creds');
const path = require('path');

runBackend({
   
  	//Directories of required files
  	controllersDir: path.resolve(__dirname, 'controller'),
    domainsDir: path.resolve(__dirname, 'domain'),
    repositoriesDir: path.resolve(__dirname, 'repository'),
    modelsDir: path.resolve(__dirname, 'model'),

  	// soon more documentation about dependency injection
  	injectionDir: path.resolve(__dirname,'injection')
 
  	//If true, force sync with database, 
  	//droping and creating database
  	forceSync: false,
   
  	//Secret that will use security token
  	secret: 'das87hjh82e8s545gf78488f41h57',
  	database: {
      dialect: 'sqlite',
      storage: path.resolve(__dirname, 'database/db.sqlite')
    }
    
});

Run the command node index.js in command line and wala, your backend app is

The first endpoint

Inside the controller folder create a file named hello-world.controller.js and write the next block of code:

const { Controller } = require('rest-creds').types;

class HelloWorldController extends Controller{
    async get(req, res){
	    res.json({
		    message:'Hello World!'
	    });
    }
}

module.exports = HelloWorldController;

run the application and go to http://localhost:9999/api/helloworld/, you will see something like this as a response:

{
    "message":"Hello World!"
}

You've created your first web service with rest-creds.

The way to create post, put and delete method services its the same as get, just create a async function in controller with the name of the method you want.

Parameters in URL routes

Also you can declare your webservices as objects or arrays in order to specify parameters, sub routes or create many services of the same method, lets focus on the class as the next code:

class HelloWorldController extends Controller{
    get:[{
	    route:'/:id', /** localhost:999/api/helloworld/1**/
	    async callback(req, res){
		    res.json({
			    message: `ID is ${req.params.id}`
		    });
	    }
    }]
}

Adding heads to services

Heads in rest-creds allow us to pre process the request to our endpoints, as example validate that only logged user can use some web services. Heads can be added using the getters postHeads, getHeads, putHeads and deleteHeads, also if the service is declared by an object them can writed inside this throught the property heads as an array of heads no matter what method is. Rest-creds includes some heads in the framework, like authorized head, and there are some more on development.

Heads can be added like this:

class HelloWorldController extends Controller{

  get getHeads(){
    return [
      this.heads.authorized
    ];
  }
  async get(req, res){
    res.json({
      message:'You are authorized!'
    });
  }
	
}

Also heads can be done like this:

get getHeads(){
    return [
	    (req, res, next) => {
		    console.log('This happens before get service');
		    next();
	    }
    ];
}

Validations in domain

Domain is the layer where business rules are and it is easy to build as controller, it includes the functions from validator, and it only requires to add a file named hello-world.domain.js to domain folder with the next code:

const { Domain } = require('rest-creds').types;

class HelloWorldDomain extends Domain{
    isEmailValid(email){
	    if(!this.isEmail(email)){
		    throw {
			    message: 'Email has a invalid format.'
		    };
	    }
    }
}

module.exports = HelloWorldDomain;

Domain layer it automatically adds to controller property domain by its name:

async get(req, res){
    try{
	    this.domain.isEmailValid(res.params.email);
	    res.json({
		    message: 'Email is valid!'
	    });
    } catch(e){
	    res.error(e);
    }
}

In this case rest-creds detects that HelloWorldController has a domain because the class name of controller and domain, both has "HelloWorld".

Creating a table

As other elements of rest-creds, it only requires to add a file to it respective folder, sequelize do the magic. This time is model folder, create a file named hello-world.model.js with the next content:

const { Model } = require('rest-creds').types;

class HelloWorldModel extends Model{
	get definition(){
		return {
			id: {
				type: this.seq.UUID,
				primaryKey: true,
				defaultValue: this.seq.UUIDV4
			},
			name:this.seq.STRING
		};
	}
}

module.exports = HelloWorldModel;

Relations between models

Relations can be added in both ways, from child or parent table, the relations its declared throught the getter relations as in the next example:

class HelloCountryModel extends Model{
    
    get definition(){
	    return {
		    id:this.seq.INTEGER,
		    name: this.seq.STRING
	    };
    }
    
    get relations(){
	    return [
		    {belongsTo:'helloWorld'},
		    {hasMany:'helloState'}
	    ];
    }
    
}

Repositories is our access to data

Creating a repository it follows the same convention as other elements of rest-creds, create a file named hello-world.repository.js to repository folder and write the next content to the file:

const { Repository } = require('rest-creds').types;

class HelloWorldRepository extends Repository{
	
}

module.exports = HelloWorldRepository;

Rest-creds will automatically associate this repository to HelloWorldController and will be available throught the property repository and will has the property model on its, wich is the HelloWorldModel, also the repository has access to finding data functions as the next example:

class HelloWorldController extends Controller{
    async get(req, res){
	    res.json(await this.repository.findAll());
    }
}

For complex data you can add functions to repository, and them are accesible throught the property repository in controller as findAll function:

class HelloWorldRepository extends Repository{
		async getComplexData(){
    		const response = this.findAll();
    		....
    		return response;
		}
}

And call it in contrller like this:

const response = await this.repository.getComplexData();

Also there is a property called repositories wich it has a reference to all the repositories of your application:

this.repositories.otherRepo.findAll();

soon more documentation...

Package Sidebar

Install

npm i rest-creds

Weekly Downloads

0

Version

0.3.5

License

MIT

Last publish

Collaborators

  • karurosux