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

api-common

v1.2.2

Published

A simple logger and middleware implementation for use with Syslog as logging target

Downloads

850

Readme

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 Formatters
    const Fmt =  require('api-common').Formatter;
    const err = new Error('Any error you want to log');
    const reporter = 'Place from which this log message is emitted';
    const appName = 'sample-app';
    Fmt.buildLogMessage(req, res, err, appName, reporter);
  • Ping and app info endpoints

Steps

  1. Install the package

    npm i api-common --save
  2. Using the logger

    'use strict';
    
    // Get the logger instance configured with provided config
    const logger = require('api-common').getLogger('fullPathToLogFile');
    
    // export it so that your rest of the application can simply consume
    // this preconfigured logger.
    module.exports = logger;
  3. Using the middleware

    'use strict';
    
    const SwaggerExpressMiddleware = require('swagger-express-mw');
    const SwaggerUIMiddleware = require('swagger-ui-middleware');
    
    // A very good middleware that works out of the box, please use it.
    const ResponseTimer = require('response-time');
    
    // STEP 1: Load the appconfig.json that has the logging config in it.
    const appConfig = require('./../config/appconfig.json');
    
    // STEP 2: Initialize the middleware
    const CustomMiddleware = require('api-common').Middleware.init(appConfig.appName);
    /*
      The app name can be provided any way you can.
    */
    
    const port = process.env.PORT || appConfig.port;
    const config = {
        appRoot: "./src" // required config
    };
    let app = require('express')();
    
    // STEP: 3 Start wiring up the middleware [Order is important]
    app.use(CustomMiddleware.CorrelationIdMiddleware);
    app.use(CustomMiddleware.RequestResponseMiddleware);
    app.use(ResponseTimer());
    
    SwaggerUIMiddleware.hostUI(app,{
        path: appConfig.swaggerUiPath,
        overrides: "./src/swagger"
    });
    
    SwaggerExpressMiddleware.create(config, function (err, swaggerExpress) {
        if (err) {
            throw err;
        }
    
        // install middleware
        swaggerExpress.register(app);
    
        // Wire error handlers after this line
    
        //STEP:4 ALWAYS put this middleware in the end. It ends request pipe.
        app.use(CustomMiddleware.ErrorLoggingMiddleware);
    });
    
    
    module.exports = app; // for testing
    
    app.listen(port);
  4. Using the logger from within Sequelize model initializers

    'use strict';
    const path = require('path');
    const dbconf = require('../../../config/dbconfig');
    // here we use the logger wrapper from #2
    const logger = require('../helpers/Logger');
    
    let Sequelize = require('sequelize');
    dbconf.CONNECTION_CONFIG.logging = function(sqlInfo){
        logger.debug({ sql: sqlInfo ,from: path.basename(__filename) });
    };
  5. Using the ping and app info endpoints

    Pass in the express app and the configuration you want to show in the app info endpoint.

    require('api-common').StatusInformation.initializeStatusEndpoints(app, { example: 'configuration' });
  6. Important note when using within Swagger projects.

    • in ./config/default.yaml if it looks like

      # pipe for all swagger-node controllers
          swagger_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 controllers
          swagger_controllers:
            - cors
            - swagger_security
            - _swagger_validate
            - express_compatibility
            - _router