4.0.0 • Published 1 year ago
hmpo-app v4.0.0
hmpo-app forms framework bootstrap
Usage
Simple usage
const { setup } = require('hmpo-app');
const { router } = setup();
router.use('/', require('./routes/example'));Extended usage
const {
setup,
featureFlag,
config,
logger,
redisClient,
linkedFiles
} = require('hmpo-app');
const {
app,
staticRouter,
router,
errorRouter
} = setup({
option: 'value'
});See example app for more details
setup()
setup(options)Bootstrap the app. run this as early on as possible to init the logger before it is used.
Returned object:
appthe top-level express appstaticRouteran express router before session is initialisedrouteran express router after session is initialisederrorRouteran express router before the generic error handling used to handle custom errors
Options object:
Any of these options (except for config) can also be specified in a config file. The options passed to setup() override the options loaded from config files.
configiffalseno config will be loaded
APP_ROOToverride app root directory detectionfiles='config/default(.json|.yaml|.yml)'array of config files to try to load. Missing files will fail silently.envVarName='HMPO_CONFIG'environment variable to parse to override config values.commandLineSwitch='-c'command line switch to load additional config files.merge=truemerge new config with config from previous calls to setup.
env=NODE_ENVenvironment variable or'development'environment.
port=3000port to bind to. Iffalsethe app will not listen to a port.host='0.0.0.0'host to bind to.
logsseehmpo-loggeroptions passed to logger. Seehmpo-loggerfor defaults. Iffalseno logger is initialised.requestLogging=trueenable request logging (excluding public static files).
redisiffalseredis is not initialised
connectionStringconnection url used for connecting to a redis instancehosthost name for connecting to a redis instanceport=6379port for connection to a redis instance...otherOptionsany other options are passed toredis- If neither
connectionStringorhostandportare specified an in-memory redis is used
errorsiffalseno error handler is set
startUrl='/'url to redirect to if a deep page is accessed as a new browser. Can be afunction(req, res).pageNotFoundView='errors/page-not-found'view to render for page not found.sessionEndedView='errors/session-ended'view to render if session is not found/expired.defaultErrorView='errors/error'view to render for other errors.
urls
public='/public'base URL for public static assets.publicImages='/public/images'base URL for public sttic images.version='/version'base URL for version endpoint, orfalseto disable.healthcheck='/healthcheck'base URL for healthcheck endpoint, orfalseto disable.
publicDirs=['public']array of paths to mount on the public route, relative toAPP_ROOT.publicImagesDirs=['assets/images']array of paths to mount on the public images route, relative toAPP_ROOT.publicOptions={maxAge: 86400000}options passed to the express static middleware.
views='views'array of view directories relative toAPP_ROOT.nunjucksoptions passed tonunjuckstemplatinng contructor, orfalseto disable
dev=env==='development'runnunjucksin developer mode for more verbose errors.noCache=env==='development'don't cache compiled template files.watch=env==='development'watch for changes to template files....otherOptionsany other options are passed tonunjucks.configure
locales='.'array of locales base directories (containing a'locales'directory) relative toAPP_ROOT.translationoptions passed tohmpo-i18ntranslation library, orfalseto disable
noCache=env==='development'don't cache templated localisation strings.watch=env==='development'watch for changes to localisation files.allowedLangs=['en','cy']array of allowed languages.fallbackLang=['en']array of languages to use if translation not found is current language.cookie={name: 'lang'}cookie settings to use to store current language.query='lang'query parameter to use to change language, orfalseto disable....otherOptionsany other options are passed tohmpo-i18n
modelOptionsconfiguration for model options helper to be used withhmpo-model
sessionIDHeader='X-SESSION-ID'session ID request header to pass through to models.scenarioIDHeader='X-SCENARIO-ID'stub scenario ID request header to pass through to models.
helmetconfiguration for Helmet, orfalseto only use frameguard and disablex-powered-by.disableCompression=falsedisable compression middleware.
cookiesconfiguration for cookie parsing middleware
featureFlag
getFlags(req)return all session and config feature flagsisEnabled(flag, req)check if a feature flag is enabled in session or configisDisabled(flag, req)check if a feature flag is disabled in session or configredirectIfEnabled(flag, url)middleware to redirect if a flag is enabledredirectIfDisabled(flag, url)middleware to redirect if a flag is disabledrouteIf(flag, handlerIf, handlerElse)middleware to run different handler depending on status of a feature flag
const { featureFlag } = require('hmpo-app');
const enabledMiddleware = (req, res, next) => res.send('flag enabled');
const disabledMiddleware = (req, res, next) => res.send('flag disabled');
router.use(featureFlag.routeIf('flagname', enabledMiddleware, disabledMiddleware));config()
config(path, defaultIfUndefined)get a value from loaded config by dot separated path, or a default if not found or undefined. Id any part of the path is not found, the default will be returned.
const { config } = require('hmpo-app');
const value = config.get('config.path.string', 'default value');logger()
logger(name)get a new logger with an optional name
const { logger } = require('hmpo-app');
const log = logger(':name');
log.info('log message', { req, err, other: 'metedata' });
// or
logger().info('log message', { req, err, other: 'metedata' });redisClient()
redisClient()return redis client
const { redisClient } = require('hmpo-app');
redisClient().set('key', 'value');