npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ocbesbn-web-init

v2.2.31

Published

Basic web server setup for OpusCapitaBusinessNetwork REST services.

Downloads

5

Readme

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
    }
}