hexa-onion

Basic helper module for dependency injection in an hexagonal / onion architecture.

Usage no npm install needed!

<script type="module">
  import hexaOnion from 'https://cdn.skypack.dev/hexa-onion';
</script>

README

hexa-onion

Basic helper module for dependency injection in an hexagonal / onion architecture.

Overview

This light 2-classes modules helps:

  • building an application layer by layer, wrapped one around the other
  • populating layers with services
  • accessing dependencies from a service:
    • either other services from the same layer
    • or "port" services from the immediate inner layer
    • or "plugin" services from the immediate outer layer

Installation

$ npm install hexa-onion

Usage

Build a 2 layers architecture with its services:

// ./index.js
const hexaOnion = require("hexa-onion");

// Domain layer
let dom = new hexaOnion.Layer();
dom.addService("answer", require("./dom/answer"));
dom.addPort("question", require("./dom/question"));

// Application layer
let app = new hexaOnion.Layer(dom);
app.addPlugin("db", require("./app/json-db"));
app.addPort("server", require("./app/express-server"));

Write service classe by extending the Service class, for services to access :

  • other services of the same layer using this.services :
// ./dom/question
const hexaOnion = require("hexa-onion");

class Question extends hexaOnion.Service {
    async ask() {
        let answer = await this.services.answer.getAnswer();
        return answer;
    }
}

module.exports = Question;
  • plugin services of the outer layer using this.plugins:
// ./dom/anwser
const hexaOnion = require("hexa-onion");

class Answer extends hexaOnion.Service {
    async getAnswer() {
        let answer = await this.plugins.db.readAnswer();
        return answer;
    }
}

module.exports = Answer;
  • and/or port services of the inner layer using this.ports:
// ./app/express-server
const hexaOnion = require("hexa-onion");
const express = require("express");

class ExpressServer extends hexaOnion.Service {
    listen() {
        let app = express();
        app.get("/question", async function(req, res) {
            res.send(await this.ports.question.ask());
        });
        app.listen(8080, function() {
            console.log("Server listening on port 8080...");
        });
    }
}

module.exports = ExpressServer;

And finally start the application by calling one of the external ports:

// back to ./index.js
inf.ports.server.listen();