@opuscapita/web-init
v4.8.0
Published
Basic web server setup for OpusCapita Business Network.
Downloads
1,317
Readme
@opuscapita/web-init
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 @opuscapita/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:
// Optional health check callback to determine whenever the system is healthy/ready so it can e.g. be added/removed from an API gateway or load balancer automatically.
module.exports.onHealthCheck = async function()
{
// Always return true or false but DO NOT run time consuming tasks inside this function as it has to retun in time.
return true;
}
// Make sure this functions is async or returns a promise.
module.exports.init = async 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'));
}
Go to your code file and put in the minimum setup code.
const server = require('@opuscapita/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.
(async () =>
{
await server.init({
server : {
port : {{your-service-port}},
events : {
onStart : () => console.log('Server ready. Allons-y!')
}
}
});
})();
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)
@opuscapita/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');
});
I18nProxy
The web-init library contains a special proxy class enveloping the I18nManger to provide additional functionality. As the basic API is the exact same as the one found in I18nManager, the I18nProxy class extends these API by allowing all methods to be called as xxxObject() which then returns an object with all translated or formatted values for all languages available.
Example:
app.get('/hello', (req, res) =>
{
const result = req.opuscapita.i18n.getMessageObject('world');
res.send(result);
/**
* Sends:
* { "en" : "World", "de" : "Welt" }
*/
}
});
Response context (res.opuscapita)
@opuscapita/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.
EventClient
The web-init module also provides a fully initialized instance of EventClient. To enable this, the configuration value server.enableEventClient has to be set to true. If this is enabled, every incoming request will contain an event client instance (req.opuscapita.serviceClient) ready to use.
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,
useHotMiddleware: false,
htmlWebpackPlugin : {
enable : false,
filename: 'index.html'
},
configFilePath : process.cwd() + '/webpack.conf.js'
},
middlewares : [ ],
requestHeadersToResponse : [ 'Correlation-Id' ],
appVariables : { },
enableIdentity : true,
enableBouncer : true,
bouncer : {
registerPermissions : {
retryTimeout : 1000,
retryCount : 30
}
},
enableEventClient : true,
cacheControl : {
defaultAge : 3600,
cachableEndpoints : [ '^/static/*', '^/public/static/*' ],
nonCachableEndpoints : [ '^/api/*', '^/public/api/*' ]
},
publicApis : [ '*' ],
noLogEndpoints : [ '^/api/list/apis$', '^/api/health/check$' ],
maxMemory : process.env.MAX_MEMORY || -1
},
logger : new Logger(),
serviceClient : {
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
}
}
Migration instruction
Version 2.x to 3.x
Most important change is the use of Op.eq
, Op.neq
, Op.gt
, etc. operators
instead of string literals like $eq
, $neq
, $gt
.
Version 3.x to 4.x
You should update your node version - web-init was tested with node 14.
The libraries are using local session storage which was introduced in node 10. It keeps the correlation ID (in the future it might keep more items).
Though not yet used in v4.0.3, it is planned to update other andariel libraries to improve traces. Those libraries could become also combined to avoid versioning issues. Keep track on the versions. We should follow the conventional npm versioning: patch versions for bugfixes or non-visible changes, minor for new features, major for breaking changes that require changes from your side (thus version 4.x should work on your code without any extra changes)