Skip to content
Bartosz Łaniewski edited this page Mar 28, 2018 · 7 revisions

Inra Server is a set of JavaScript libraries for creating back-end solutions on a higher level of abstraction. This project is very experimental, as it brings to life patterns very rarely seen in Node.js such as inversion of control, dependency injectors, autoloaders.

Installation

Inra Server is written using ES2015 modules. Create a custom bundle using Rollup, Webpack, or your preferred bundler. To import Inra into your ES2015 application, just import Inra modules that you need:

import Server from "inra-server-http";
import Socket from "inra-server-socket";
import Container from "inra-server-container";

A small taste of Inra

Bootstrap

const app = new Server({
  host: process.env.SERVER_HOST,
  port: process.env.SERVER_PORT,
});

// Use Koa.js as core engine (server is adaptive):
app.setEngine(new Koa());
app.setRouter(new Router());

// Set handlers for Middleware and Routers:
app.addHandler("Middleware", Server.middlewareHandler);
app.addHandler("Router", Server.routerHandler);
app.addHandler("default", (resource, app) => resource(app));

// Register some global middlewares:
app.use(body());
app.use(logs());
app.use(cors({origin: "*"}));

// App can be used as a dependency injector:
app.models = models;
app.logger = logger;

// Load all the components automatically:
try {
  load("api/middlewares", src => app.import(src));
  load("api/routes", src => app.import(src));
  load("api/stuff", src => app.import(src));
} catch (error) {
  logger.error(error);
}

Router

class FooRouter {
  // Server automatically populates imported Routers with dependencies
  constructor({models, logger}) {
    this.models = models;
    this.logger = logger;
  }

  @post("some/path")
  async create(ctx, next) {
    // …
  }

  @get("some/path/:id?")
  async read(ctx, next) {
    // …
  }

  @patch("some/path")
  async update(ctx, next) {
    // …
  }

  @del("some/path/:id?")
  async delete(ctx, next) {
    // …
  }
}

Middleware

class FooMiddleware {
  // Server automatically populates imported Middlewares with dependencies
  constructor({models, logger}) {
    this.models = models;
    this.logger = logger;
  }

  async before(ctx, next, ...params) {
    // …
  }

  async handle(ctx, next, ...params) {
    // …
  }

  async after(ctx, next, ...params) {
    // …
  }
}