Giter Site home page Giter Site logo

donode's Introduction

donode

Superfast & Lightweight node framework for building RESTful APIs.

Simple . Flexible . High Performance . ES2015+

Enables developers to focus on writing reusable application logic in a highly modular approach.

Use donode-cli, to get started.

**NOTE: Requires node 8.0 or higher **

High Performance

Here are the performance results.

Documentation

App Structure

Create the app using donode-cli, it is as simple and modular as

  • app
    • controllers
    • middleware
    • headers.js
    • routes.js
  • env
    • development.env.js
    • production.env.js
  • app.js

Routing

One Place for all your routes and they go into app/routes.js.

A Route can be as simple as

{
  path: '/hello',
  method: 'GET',
  handler: 'HelloController@get'
}
Property Type Description
path string url for the route
method string can be one of GET, POST, PUT, UPDATE, DELETE.
handler string format: SomeController@method
Here in this format SomeController is the controller (a class) located in app/controllers directory.

And method (name after @) is the name of the method in the given controller, which gets called and send response.

more details available in controllers section.

Advanced Routing

A Route can take options like middleware, headers, children.

{
  path: '/user/{id}',
  method: 'GET',
  handler: 'UserController@get',
  middleware: ['Auth'],
  headers: ['allow-cors'],
  children: [{
  	path: '/settings',
    method: 'GET',
    handler: 'UserController@settings',
  }]
}
Property Type Description
path string A route can have params in its path.
syntax: {param}

example:
/user/{id} can respond to /user/1, /user/123 etc..
method string values are not limited GET, POST, PUT, UPDATE, DELETE.
can be any type of request that server can listen to. (HEAD, OPTIONS etc..)
handler string A controller can be from a sub directory inside controllers directory.
syntax: subdirectory/SomeController@method
here in this SomeController is located in app/controllers/subdirectory.
middleware array
or
object
A Middleware is an intermediate handler which can be used to perform some pre-checks such as Auth.
It is a class located in app/middleware directory and will be called before the handler method.

Array Syntax: ['Middleware1', 'Middleware2']

A list of strings which are the names of the classes from app/middleware directory. When attached to a route, these will be called in the given order before the actual handler.

more details available in middleware section.

Object syntax:
{
   all: ['Middleware1'],
   only: ['Middleware2'],
   children: ['Middleware3']
}


-- all: attached to current the route and all its children.
-- only: attached only to current route.
-- children: attached to all the children, but not to current route.

Note: All are optional. Any of them can be given/ignored.

Order: middleware defined under all, children which are coming from parent routes (if any), then all, only of current route.
headers array headers property allows to attach a set of headers that can to be sent along with the response for every request.
It takes an array of stings which are defined in app/headers.js.

syntax
['allow-cors', 'json-content']

Note: currently headers attached to a route will apply only to it. Not to children. Object syntax is yet to come !!!
children array Routes can be nested with this attribute.
This takes list of sub-routes which takes same set of above properties.

example route config
{
  path: '/user/{id}',
  method: 'GET',
  handler: 'UserController@get',
  children: [{
     path: '/settings',
     method: 'POST',
     handler: 'UserController@settings'
  }]
}

this will register the routes
GET: /user/{id}
POST: /user/{id}/settings

Controllers

app/controllers: A place for all controllers of the app.

A controller is a class which inherits Controller from donode, and has the handler methods of a route.

const Controller = require('donode').Controller;

class HomeController extends Controller {
  constructor() {
    super();
  }

  get(request, response) {
    response.send({
      'app': 'works !!!'
    });
  }
}

module.exports = HomeController;

The method get(request, response) will be the handler for a route.

handler: 'HomeController@get'

It gets request, response as params.

Request

It is a native Node Request object. Along with default properties it also contains

Property Route Values
query /user?p1=123&p2=donode { p1: 123, p2: 'donode' }
params /user/{id} { id: 123 }
body - payload sent along with request
headers - headers sent along with request
url - { }
originalUrl /user/{id} /user/123
method - GET, POST, PUT, DELETE etc..

Response

It is a native Node Response object. Along with default properties it also contains

Method definition Description
send send([response_code,] responseObject) It takes optional response code and a response object which whill be sent.

default: 200 (OK)
reject reject([response_code], responseObject) takes optional response_code and rejection responseObject.

default: 401 (bad request)
setHeader setHeader(type, value) takes header type and value

Middleware

const Middleware = require('donode').Middleware;

class Auth extends Middleware {
  constructor() {
    super();
  }

  handle(request, response, next) {
    // do some auth validation here

    // if (not authorized)
    // return response.send(401, { some: 'error data' });

    // else (proceed to the controller hander)
    return next();
  }
}

module.exports = Auth;

Note:

When response.send() or response.reject() are called in a middleware, the call chain stops and handler method will not be called.

Environments

Environments for the app can be managed by creating corresponding configuration file

env/.env.js

This configuration can be used with NODE_ENV while running the app.

$ NODE_ENV= node app.js

Examples:

NODE_ENV=production node app.js
NODE_ENV=stage node app.js

Without NODE_ENV it defaults to development.env.js.

donode's People

Contributors

madhusudhand avatar nikhilesh-kv avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

donode's Issues

display proper error message when module.exports is missing in controller

error:

/Users/madhusudhanad/madhu/os/donode-cli/blueprints/v1/node_modules/donode/lib/helpers/route-helper.js:139
this._controllers[controllerKey] = new ControllerClass();
^

TypeError: ControllerClass is not a constructor
at RouteHelper._processRoute (/Users/madhusudhanad/madhu/os/donode-cli/blueprints/v1/node_modules/donode/lib/helpers/route-helper.js:139:42)
at RouteHelper._processRouteConfig (/Users/madhusudhanad/madhu/os/donode-cli/blueprints/v1/node_modules/donode/lib/helpers/route-helper.js:79:30)
at RouteHelper.collectRoutes (/Users/madhusudhanad/madhu/os/donode-cli/blueprints/v1/node_modules/donode/lib/helpers/route-helper.js:58:10)
at Router.collectRoutes (/Users/madhusudhanad/madhu/os/donode-cli/blueprints/v1/node_modules/donode/lib/router.js:43:32)
at Server.create (/Users/madhusudhanad/madhu/os/donode-cli/blueprints/v1/node_modules/donode/lib/server.js:34:17)
at Object. (/Users/madhusudhanad/madhu/os/donode-cli/blueprints/v1/app.js:8:25)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)

improve request object

current:

  1. queryParams
  2. routeParams
  3. body
  4. headers
  5. url
  protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search: '',
  query: {},
  pathname: '/',
  path: '/',
  href: '/' 
  1. originalUrl
  2. method
  3. getContentType()

need

  1. ip
  2. params (which is equivalent to routeParams
  3. subdomains
  4. isXHR
  5. protocol (it is part of url as well)
  6. route

improve response object

current

  1. send([responseCode,] responseObject)
  2. reject([responseCode,] responseObject)
  3. end()
  4. setHeader(type, value)
  5. headersSent ? (boolean)

need

  1. setHeaders(array of objects)
  2. status(statusCode) -- a method which could be chained before send or reject.
  3. headers(array of objects) -- a method which could be chained before send or reject.
  4. redirect()

make the handlers async

User can't perform some async operations such as timeout or making another http call from inside handler.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.