Skip to content

L. Router

Jonathan Casarrubias edited this page May 3, 2018 · 2 revisions

alt text

Description

In this section, you will learn how to use the OnixJS Router.

The OnixJS Router provides features that allow you to either serve Static Files or to create REST Endpoints within your SOA Service in a middleware pattern form.

If you understand middlewares from frameworks like Express.JS then you will easily understand this functionality from the OnixJS Framework.

Even though OnixJS is not built on top of Express or any other framework, it does support middlewares, providing compatibility with any module that you are able to use in Express, KOA or any middleware based framework.

Router Example

import {
  Component,
  OnixHTTPRequest,
  Router,
  Inject,
  ErrorResponse,
} from '@onixjs/core';
import {MyService} from './my.service';
import {MyModel} from './my.model';
import {MyRenderer} from './my.renderer';

// Yes!!! middleware based modules are compatible because we love you
// And we want you to be happy :)
import * as bodyParser from 'body-parser';
import * as http from 'http';

// Create a Router Component to either serve static files or rest endpoints
@Component()
export class RouterComponent {

  // As any other component, you still can inject services, models, etc.
  @Inject.Service(MyService) service: MyService;
  @Inject.Model(MyModel) model: MyModel;
  @Inject.Renderer(MyRenderer) renderer: MyRenderer;

  async init() {
    console.log('Router INITIALIZED');
  }

  @Router.Use()
  async urlencodedParser(req, res, next) {
    bodyParser.urlencoded({extended: false})(req, res, next);
  }

  @Router.View({
    endpoint: 'some/static/file',
    file: 'my.static.file.html',
  })
  async myView(req: OnixHTTPRequest, data: Buffer) {
    return this.renderer.process(data.toString(), { param: 'HelloWorld' });
  }

  @Router.Param({name: 'user_id', as: 'user'})
  async param(req: OnixHTTPRequest, user_id) {
    return this.model.find({ id: user_id });
  }

  @Router.Get('/users/:user_id')
  async confirmEndpoint(req: OnixHTTPRequest, res: http.ServerResponse) {
    // This user was passed from the previous middleware using @Router.Param
    console.log('Some User', req.user);
    res.write(JSON.stringify(req.user));
    res.end();
  }

  @Router.Post('/some/endpoint')
  async confirmEndpoint(req: OnixHTTPRequest, res: http.ServerResponse) {
    console.log(req.body); // Thanks bodyParser :)
  }

  @Router.Static('./some.directory')
  async assets(req: OnixHTTPRequest, data: Buffer) {
    return data;
  }
}

The example above demonstrate several ways to use the router, either you implement a middleware based module by decorating a method using @Router.Use, or creating views, rest endpoints, handling route params etc.

HINT: You are not limited to Get and Post HTTP Methods, you can actually use any other HTTP Method such as @Router.Patch, @Router.Put, etc.

Clone this wiki locally