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

utils-abstractions

v1.2.10

Published

A collection of utilities and abstractions for logging, middlewares, etc.

Downloads

439

Readme

Utils Abstractions

A collection of utilities and abstractions for logging, middlewares, etc.

API Documentation

Logger

BaseLogger

Defines the logger's structure.

interface BaseLogger {
    info(message: string, meta?: any): void
    debug(message: string, meta?: any): void
    error(message: string, meta?: any): void
    warn(message: string, meta?: any): void
    http(message: string, meta?: any): void
}

BaseMetadataFields

Defines the fields for the metadata of logging. All the new definitions must extend from this interface.

interface BaseMetadataFields extends Record<string, string | number | unknown> {
    domain?: string
    layer?: 'Application' | 'Infrastructure' | 'Presentation' | 'None' | string
    context?: string
}

Log message structure

The structure of the log messages is the next:

[2023-03-30 12:16:16.0761 PM] [log-level] [domain.layer.context]: Database connected

These fields are based in the concepts of Clean Architecture. For an initial approach domain can be similar to a module or submodule.

LoggerContainer

Stores implementations of BaseLogger.

Because you can have different logging mechanisms (console, files, stream, etc.) this container keeps all the defined implementations and allows you, either all or one definition depending on the needed context.

Each implementation is mapped to a name, this allows you to select an instance to use. In the case we want to use all the registered implementations you can use the log level method that you need.

Also, it is configured to be used as dependency with Inversify.

class LoggerContainer implements BaseLogger {...}

Errors

  • LoggerAlreadyRegisteredError
  • LoggerNotExists

Example

// Register a new logger, in case there already exists throws an error
loggerContainer.addLogger('winston-console', new WinstonLogger())

// Get an instancia, in case there is no exists throws an error
const logger = loggerContainer.getLogger('winston-console')

logger.debug('Hello ..')

// Delete an instance, in case there is no exists throws an error
loggerContainer.removeLogger('winston-console')

// Use all registered loggers
loggerContainer.info('Logging for all')

Logger Implementations

  • WinstonLogger: Using winston.
  • SeqLogger: Using datalust/winston-seq.
    • Depends on SEQ_SERVER and SEQ_TOKEN.
  • LokiLogger: Using winston-loki.
    • Depends on LOKI_SERVER, LOKI_INTERVAL and LOKI_APP_LABEL env.
    • In case that LOKI_APP_LABEL is not assigned the default value is logger-container.

getRequestData

Adds information about the request in the metadata. Sets the fields:

  • url
  • method

reassign: If true assigns the values in the object directly instead of create a copy. Default to false.

function getRequestData(metadata: BaseMetadataFields, reassign?: boolean): BaseMetadataFields

showDebugQuery

Add the query to the logs. Depends on the env SHOW_QUERY with the value show.

function showDebugQuery(message: string, query: string): string

CORS

corsOptions

Defines a configuration for allowed origins. The list of origins comes from then env CORS_ORIGINS in a single string separated by commas.

Example

const corsOptions: CorsOptions

// CORS_ORIGINS = https://dev.test.app,https://admin.test.app

credentialsHeader

Sets the header Access-Control-Allow-Credentials to the request based on the CORS_ORIGINS.

function credentialsHeader(req: Request, res: Response, next: NextFunction)

Middlewares

errorHandler

An express error middleware to handle error responses.

function errorHandler(err: any, req: Request, res: Response, next: NextFunction)

HelmetConfig

The Helmet middleware with custom options for:

  • hidePoweredBy
  • dnsPrefetchControl
  • frameguard
  • noSniff
  • xssFilter
const HelmetConfig = helmet({ ... })

httpRequestData

Fetch data from the request and keep it in memory. Works together a logger, and it takes the values of:

  • body
  • params
  • query
  • headers
  • url
  • method
function httpRequestData(logger: BaseLogger): (req: Request, res: Response, next: NextFunction) => void

morganCustomLogger

A custom implementation of morgan for http request.

function morganCustomLogger(logger: BaseLogger): Handler<IncomingMessage, ServerResponse<IncomingMessage>>

Auth

JwtStrategyOptions

Default configurations for passport-jwt with:

  • Extract token from Authorization Header (Bearer)
  • Issuer
  • Algorithms

Requires the env JWT_ACCESS_SECRET, JWT_ISSUER and JWT_ALGORITHM

const JWT_STRATEGY_OPTIONS: StrategyOptions