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 🙏

© 2026 – Pkg Stats / Ryan Hefner

commonly-used-methods

v0.0.18

Published

Commonly used methods

Readme

My commonly used methods

Detailed usage instructions are in project's tests folder.

configureFileLogger

Do not forget to set environment variables:

  • LOG_FILE_NAME="%DATE%-current.log"
  • LOG_FOLDER="/var/log/service"
  • LOG_LEVEL="debug"
  • LOG_MAX_SIZE="20m"
const winston = require('winston');
const configureFileLogger = require('commonly-used-methods').configureFileLogger;
const state = {
  environment: process.env,
  makeLogger: winston.createLogger,
  LogTransport: require('winston-daily-rotate-file')
};

await configureFileLogger(state);

state.logger.log('info', 'It works fine!');

commitTransaction

Fires if there are non completed transaction and no error in state container.

const createTransaction = require('commonly-used-methods').createTransaction;
const commitTransaction = require('commonly-used-methods').commitTransaction;
const state = {
  makeTransaction: knex.transactionProvider()
};

createTransaction(state);

// Here use transaction to operate with database

await commitTransaction(state);

expect(state.transactionResult).not.toBeUndefined();

createTransaction

const createTransaction = require('commonly-used-methods').createTransaction;
const knex = require('knex')({ client: 'pg', connection: { host: 'localhost' }});
const state = {
  database: knex
};

createTransaction(state);

expect(state.error).toBeUndefined();
expect(typeof state.transaction).toEqual('function');

executeHttpRequest


const executeHttpRequest = require('commonly-used-methods').executeHttpRequest;
const state = {
  httpTransport: require('https'),
  httpRequestUrl: 'https://egorov.space/api/user/login',
  httpRequestOptions: {
    method: 'POST',
    headers: {
      'content-type': 'application/json'
    }
  },
  httpRequestEncoding: 'utf-8',
  httpRequestBody: {
    login: 'jack',
    password: 'P@ssw0rd'
  }
};

await executeHttpRequest(state);

const value = JSON.parse(state.httpResponseBody);

expect(typeof value.access_token).toEqual('string');
expect(value.userName).toEqual('jack');
expect(state.httpResponseChunks).toEqual(
  [
    '{"access_token":"98092","userName":"jack"}' 
  ]
);

getUserFromCache

It expects connected Redis client in state.


const getUserFromCache = require('commonly-used-methods').getUserFromCache;
const state = {
  cache: require('redis').createClient({ host: 'x_redis' })
};

await getUserFromCache(state);

expect(state.error).toBeUndefined();
expect(state.user).toEqual({ email: '[email protected]' });

getUserPermissionsByUserIdAndPhoneAndVerify

It expects connected Redis client in state.


const execute = 
  require('commonly-used-methods').getUserPermissionsByUserIdAndPhoneAndVerify;
const state = {
  cache: require('redis').createClient({ host: 'x_redis' }),
  permission: 'Включать свет',
  user: {
    normal_phone: '7 9199998811',
    user_id: '88bc23a8af0'
  }
};

await execute(state);

expect(state.error).toBeUndefined();

getUserPermissionsFromCacheAndVerify

It expects connected Redis client in state.


const execute = 
  require('commonly-used-methods').getUserPermissionsFromCacheAndVerify;
const state = {
  cache: require('redis').createClient({ host: 'x_redis' }),
  permission: 'Включать свет',
  user: {
    user_id: '88bc23a8af0'
  }
};

await execute(state);

expect(state.error).toBeUndefined();

makeErrorResponseContent

Knows about exceptions messages from getUserFromCache, getUserPermissionsFromCacheAndVerify and validateRequestBody. Generates minimal response content for it them statusCode and body:

const makeErrorResponseContent = require('commonly-used-methods').makeErrorResponseContent;
const error = new Error('Отсутствует токен авторизации!');
const state = { error };

makeErrorResponseContent(state);

expect(state.responseContent).toEqual({
  statusCode: 401,
  body: {
    danger: error.message
  }
});
expect(state.error).toEqual(error);

makeOperationId

Generates configurable length random string. Default string length 24 characters. Requires randomBytes method attached to state container.


const makeOperationId = require('commonly-used-methods').makeOperationId;
const state = {
  environment: {
    OPERATION_ID_SIZE: '32'
  },
  randomBytes: require('crypto').randomBytes
};

makeOperationId(state);

expect(state.error).toBeUndefined();
expect(sate.operationId.length).toEqual(32);

rollbackTransaction

Fires if there are non completed transaction and error set in state container.

const createTransaction = require('commonly-used-methods').createTransaction;
const rollbackTransaction = require('commonly-used-methods').rollbackTransaction;
const state = {
  makeTransaction: knex.transactionProvider()
};

createTransaction(state);

state.error = new Error('Что-то пошло не так!');

await rollbackTransaction(state);

expect(state.transactionResult).not.toBeUndefined();

sendExpressHttpResponse

Important! There should be expressjs response object in state container.

const sendExpressHttpResponse = 
  require('commonly-used-methods').sendExpressHttpResponse;
const state = {
  responseContent: {
    statusCode: 200,
    body: 'OK'
  }
};

sendExpressHttpResponse(state);

validateRequestBody

const validateRequestBody = require('commonly-used-methods').validateRequestBody;
const state = {
  request: {
    body: {
      user_id: '938a7361cc3271923ef'
    }
  },
  requestBodyValidationRules: {
    email: {
      is_required: true,
      type: 'email'
    }
  },
  validate: require('plain-object-validation').validate
};

validateRequestBody(state);

expect(state.error).toEqual(new Error('Ошибка валидации содержимого запроса!'));
expect(state.requestBodyValidationResult).toEqual({
  errors: [
    email: [
      { is_required: true },
      { type: 'email' }
    ]
  ]
});