API Common
Features
- Logger class that logs to console in dev mode and to File in non development mode
- Middlewares for
- Request response logging
- Error handler for uncaught exceptions, 400 bad request and explicitly set 500.
- Correlation ID setting middleware
- JWT unpacking
- Error Formattersconst Fmt = Formatter;const err = 'Any error you want to log';const reporter = 'Place from which this log message is emitted';const appName = 'sample-app';Fmt;
- Ping and app info endpoints
Steps
-
Install the package
npm i api-common --save -
Using the logger
'use strict';// Get the logger instance configured with provided configconst logger = ;// export it so that your rest of the application can simply consume// this preconfigured logger.moduleexports = logger; -
Using the middleware
'use strict';const SwaggerExpressMiddleware = ;const SwaggerUIMiddleware = ;// A very good middleware that works out of the box, please use it.const ResponseTimer = ;// STEP 1: Load the appconfig.json that has the logging config in it.const appConfig = ;// STEP 2: Initialize the middlewareconst CustomMiddleware = Middleware;/*The app name can be provided any way you can.*/const port = processenvPORT || appConfigport;const config =appRoot: "./src" // required config;let app = ;// STEP: 3 Start wiring up the middleware [Order is important]app;app;app;SwaggerUIMiddleware;SwaggerExpressMiddleware;moduleexports = app; // for testingapp; -
Using the logger from within Sequelize model initializers
'use strict';const path = ;const dbconf = ;// here we use the logger wrapper from #2const logger = ;let Sequelize = ;dbconfCONNECTION_CONFIG{logger;}; -
Using the ping and app info endpoints
Pass in the express app and the configuration you want to show in the app info endpoint.
StatusInformation; -
Important note when using within Swagger projects.
-
in
./config/default.yaml
if it looks like# pipe for all swagger-node controllersswagger_controllers:- onError: json_error_handler- cors- swagger_security- _swagger_validate- express_compatibility- _router -
Make sure you remove the
onError
key. It interferes with our error handler.# pipe for all swagger-node controllersswagger_controllers:- cors- swagger_security- _swagger_validate- express_compatibility- _router
-