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

@crubn/indisi-common

v1.0.3

Published

Common components for Indisi microservices

Downloads

6

Readme

Indisi common

# Build Passing

Repository for all the components that are to be used by various microservices in the Indisi project. The aim of this is to reduce redundancies across microservices. This repository will be published as an npm packages which should be imported in the microservices.

Components

How to use

Add .npmrc file inside root directory of your project, .npmrc should contain:

@crubn:registry=https://npm.pkg.github.com/
//npm.pkg.github.com/:_authToken=PKG_TOKEN

PKG_TOKEN is a GitHub access token that has at least read:packages permission. Tutorial for creating a access token.

0. Configuration

To use modules such as mongo, redis, etc. that need configuration (host, port, etc.) to run, in the main project file, do the following

import {configure} from '@crubn/indisi-common';

// Configure the indisi common module
configure(config.get('common'));

The configuration should be as following, along with other project specific config.

{
  "common": {
    "logger": {
      "level": "LOG_LEVEL",
      "dir": "LOG_DIR",
      "mail": {
        "recipients": "LOG_MAIL_RECIPIENTS",
        "sender": "LOG_MAIL_SENDER",
        "smtp": {
          "host": "LOG_MAIL_SMTP_HOST",
          "port": "LOG_MAIL_SMTP_PORT",
          "username": "LOG_MAIL_SMTP_USERNAME",
          "password": "LOG_MAIL_SMTP_PASSWORD"
        }
      }
    },
    "mongo": {
      "host": "MONGO_HOST",
      "port": "MONGO_PORT",
      "username": "MONGO_USERNAME",
      "password": "MONGO_PASSWORD",
      "defaultDatabase":"MONGO_DEFAULT_DB"
    },
    "redis": {
      "host": "REDIS_HOST",
      "port": "REDIS_PORT",
      "password": "REDIS_PASSWORD",
      "streamThreshold": "REDIS_STREAM_THRESHOLD"
    }
  }
}

1. Helpers

import  {Constants, Messages} from '@crubn/indisi-common'

2. Logger

import {Logger} from '@crubn/indisi-common';

const logger = Logger.getInstance();

logger.fatal('The universe is a cruel, uncaring void. The key to being happy isn't to search for meaning. It's to just keep yourself busy with unimportant nonsense, and eventually, you'll be dead.');

All standard log levels are supported

3. Middlewares

import  {AuthenticationMiddleware, AuthorizationMiddleware, ValidationMiddleware, RequestProperty} from '@crubn/indisi-common'

// Use as express middlware

// Authentication
app.use(`/some-path`, AuthenticationMiddleware.authenticate);

// Authorization
// To check if org is active
app.use(`/some-path`, AuthorizationMiddleware.isOrgActive);
// To check if user is super admin
app.use(`/some-path`, AuthorizationMiddleware.isSuperAdmin);

// Validation
// validate request structure - body, path or query params
  ValidationMiddleware.validateDto(RequestProperty.BODY ,CreateProofTemplateDto)

4. Mongo

import {Mongo} from '@crubn/indisi-common';

Mongo.connect();

5. Redis (stream)

  import {Redis} from '@crubn/indisi-common';
  Redis.connect().then(()=>{
    // read streams here
     this.readStreams();
  });

  private readStreams = () => {
    Redis.readStream(config.get('redisStream.consumerGroupName'),
        config.get('redisStream.consumerName'),
        config.get('redisStream.names'),
        (streamName, stream, done)=>{
          // Do something
          logger.debug(`Received stream messages - ${streamName} - ${JSON.stringify(stream.messages)}`);
          this.streamReaders.forEach((reader) => {
            reader(streamName, stream, done);
          });
        });
  };

done() should be invoked to acknowledge that the message has been successfully processed by the reader.

6. WebApi

  import {WebApiResponse, WebApi} from '@crubn/indisi-common';

  const result = await this.proofTemplateService.createProofTemplate(orgId, proofTemplate);
  const responseData: WebApiResponse = WebApiResponse.successResponse(result);
  response.status(httpStatusCodes.CREATED).json(responseData);
.
.
.
  const response = await WebApi.instance.execute({
      httpMethod: 'POST',
      url: url,
      headers: {
        'Authorization': `Bearer ${orgWalletToken}`,
        'X-API-Key': config.get('cloudAgent.apiKey'),
      },
      body: requestBody,
    });

7. Error Handler

Pass all the errors to the error handler

  import {ErrorHandler} from '@crubn/indisi-common';

  // index.ts
  process.on('uncaughtException', (error:Error) => {
    ErrorHandler.handleError(error);
  });

  process.on('unhandledRejection', (reason: string) => {
    ErrorHandler.handleError(new Error(reason));
  });

  // app.ts
  // Error handling middleware, we delegate the handling to the centralized error handler
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
      ErrorHandler.handleError(err, res);
    });

8. Http Error

import {HttpError, Messages} from '@crubn/indisi-common';

// throw error when needed in the service
throw new HttpError(httpStatusCodes.NOT_FOUND, Messages.resourceNotFound);