ocbesbn-web-init

2.2.31 • Public • Published

ocbesbn-web-init

Coverage Status Build status

This module combines more general and common setup routines for creating a basic REST service environment. Using it may help creating a more common and comparable structure over multiple services by following conventions made by this service.


Minimum setup

First got to your local code directory and run:

npm install ocbesbn-web-init

Now you would have to set up at least one basic route file that will automatically be included by the module when initialized. The default path for routes is "./src/server/routes". This location can be changed by configuration but may not be overwritten to stay with common service conventions.

A route module can be created using the following code:

const Promise = require('bluebird');

module.exports.init = function(app, db, config)
{
    // app => express instance.
    // db => can be defined by configuration when running the .init() method.
    // config => everything from config.routes passed when running the .init() method.
    app.get('/', (req, res) => res.send('hello world'));

    return Promise.resolve();
}

Go to your code file and put in the minimum setup code.

const server = require('ocbesbn-web-init');

// You might want to pass a configuration object to the init method. A list of parameters and their default values
// can be found at the .DefaultConfig module property.
server.init({ server: { port : {{your-service-port}} } }).then(console.log);

This code applies a lot of conventions that of course can, but may not be overwritten by passing a configuration object to the init() method.


Request context (req.opuscapita)

ocbesbn-web-init adds a sub-context to every request coming in. The following properties will be available:

Additional context data might be injected by additional middleware. By default, web-init includes the useridentity-middleware which actually adds additional methods.

Example:

app.get('/hello', (req, res) =>
{
    req.opuscapita.logger.info('World');
    res.send('World');
});

Response context (res.opuscapita)

ocbesbn-web-init adds a sub-context to every response when a new request comes in. The following properties and methods will be available:

  • setMaxAge(seconds) // Maximum browser cache time.
  • setNoCache() // Disable browser caching at all.

Additional context data might be injected by additional middleware.

Example:

app.get('/hello', (req, res) =>
{
    res.opuscapita.setMaxAge(3600); // Sets browser caching to expire after one hour.
    res.send('World');
});

Health checking

As another convention, this module provides a static REST endpoint for health checking. If the web server is up and running, GET calls to /api/health/check will return "200 OK" sending you the following object:

{"message":"Yes, I'm alive!"}

Inter-Service-Communication

If desired, this module may provide a ServiceClient instance initialized with and injected into any incoming HTTP request (req.opuscapita.serviceClient). This allows you to talk to other services while automatically keeping all headers and cookies sent with the original request. This will provide a full request context towards the target service. See the serviceClient key of the DefaultConfig object.


Security

User identity

When enabled using the enableIdentity config switch, web-init automatically makes use of the useridentity-middleware which provides read-only user information from a JSON Web Token in order to identify the requesting user. Please refer to the documentation available through the middleware's repository.

Endpoint access

In addition to the built-in functionality of web-init, another module is available to ensure security on REST endpoints. When enabled using the enableBouncer config switch, defined endpoint protection is available. For further information on this, please have a look at the repository of bouncer. The required acl.json file has to be located inside the ./src/server directory.


Internationalization / Translations

This library provides access to a fully initialized instance of OpusCapita i18n. It is available through the req.opuscapita.i18n object. The language is selected by choosing the following sources in order: req.opuscapita.userData, req.opuscapita.acceptLanguage. The default fallback language is english.

In order to automatically load translations, just place an i18n folder or i18n.js file inside the src/server/routes directory.


Default configuration

The default configuration object provides hints about what the module's standard behavior is like. It is mostly recommended to leave most settings as they are and treat them more as general conventions to a common structure in order to maintain a common setup across different services. The internal middleware adds an opuscapita sub-key to every request providing addition data and actions for every request.

{
    server : {
        mode : process.env.NODE_ENV === 'development' ? this.Server.Mode.Dev : this.Server.Mode.Productive,
        security : this.Server.Security.All,
        crossOrigins : [ '*' ],
        maxBodySize : 1048576, // 1 MiB
        staticFilePath : express.static(__dirname + '/static'),
        indexFilePath : null,
        indexFileRoutes : [ '/' ],
        hostname : process.env.HOST || '0.0.0.0',
        port : process.env.PORT || 3000,
        events : {
            onStart : function(server) { },
            onEnd : function(server) { },
            onRequest : function(req, res, next) { next(); },
            onError : function(err, server) { process.stderr.write(err); }
        },
        webpack : {
            useWebpack : false,
            configFilePath : process.cwd() + '/webpack.conf.js'
        },
        middlewares : [ ],
        requestHeadersToResponse : [ 'Correlation-Id' ],
        appVariables : { },
        enableIdentity : true,
        enableBouncer : false,
        cacheControl : {
            defaultAge : 3600,
            cachableEndpoints : [ '^/static/*', '^/public/static/*' ],
            nonCachableEndpoints : [ '^/api/*', '^/public/api/*' ]
        }
    },
    logger : new Logger({ context : { serviceName : 'web-init' } }),
    serviceClient : {
        injectIntoRequest : true,
        consul : {
            host : 'consul'
        },
        caching : {
            driver : 'dummy',
            defaultExpire : 600
        },
        headersToProxy : [ 'Cookie', 'Authorization', 'From', 'Correlation-Id' ]
    },
    routes : {
        addRoutes : true,
        modulePaths : [ process.cwd() + '/src/server/routes' ],
        dbInstance : null
    }
}

Dependencies (14)

Dev Dependencies (7)

Package Sidebar

Install

npm i ocbesbn-web-init

Weekly Downloads

0

Version

2.2.31

License

Apache-2.0

Last publish

Collaborators

  • kwierchris