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

@uoj-lk/utils-node

v1.1.1

Published

Shared utilities for University of Jaffna microservices

Readme

@uoj-lk/utils-node

npm version License: MIT

Comprehensive shared utilities for University of Jaffna microservices

Provides standardized, production-ready implementations for message brokering, logging, caching, error handling, validation, and response formatting across all microservices.

✨ Features

  • 🚀 Message Broker - RabbitMQ integration with automatic reconnection
  • 📝 Logger - Winston-based logging with daily rotation and multiple transports
  • Cache - Redis operations with TTL support and automatic serialization- 💾 Database Helper - Sequelize integration with connection pooling and retry logic
  • 📋 Query Helper - Streamlined database model validation and record checks- ❌ Error Handling - Standardized error creation with Boom integration
  • Validation - Joi-based schema validation with detailed error messages
  • 📬 Response Handler - Consistent API response formatting
  • Authentication - JWT validation and token extraction middleware
  • �🔧 Helpers - Utility functions for common operations
  • 📘 TypeScript Support - Full type definitions included
  • 🔄 ES Modules & CommonJS - Supports both module systems

📦 Installation

npm install @uoj-lk/utils-node

🚀 Quick Start

import {
  logger,
  cache,
  dbHelper,
  queryHelper,
  messageBroker,
  response,
  validation,
  auth,
} from "@uoj-lk/utils-node";

// Initialize database
const sequelize = await dbHelper.setupDatabase({
  database: "myapp",
  username: "root",
  password: "secret",
  host: "localhost",
});

// Initialize cache
await cache.initCache({ host: "localhost", port: 6379 });
await messageBroker.connectToMessageBroker("events-queue");

// Use logger
logger.info("Service initialized");

// Use query helper for validation
const user = await queryHelper.checkRecordExistByAttribute(
  UserModel,
  { id: 123 },
  "User not found",
);

// Use cache
await cache.set("user:123", user, 3600);

// Send message
await messageBroker.sendToQueue("events-queue", {
  event: "user.created",
  data: user,
});

📚 Module System Support

ESM (ES Modules) - Recommended

// Import entire package
import utils from "@uoj-lk/utils-node";

// Import specific modules
import { logger, cache, messageBroker, auth } from "@uoj-lk/utils-node";

// Import from submodules directly
import { initLogger } from "@uoj-lk/utils-node/logger";
import { setupDatabase } from "@uoj-lk/utils-node/dbHelper";
import { checkRecordExistByAttribute } from "@uoj-lk/utils-node/queryHelper";
import { connectToMessageBroker } from "@uoj-lk/utils-node/messageBroker";
import { authenticateDevJWT } from "@uoj-lk/utils-node/auth";

CommonJS

// Import entire package
const utils = require("@uoj-lk/utils-node");

// Import specific modules
const { logger, cache, auth } = require("@uoj-lk/utils-node");

// Import from submodules
const { initLogger } = require("@uoj-lk/utils-node/logger");
const { setupDatabase } = require("@uoj-lk/utils-node/dbHelper");
const {
  checkRecordExistByAttribute,
} = require("@uoj-lk/utils-node/queryHelper");
const { authenticateDevJWT } = require("@uoj-lk/utils-node/auth");

📖 Usage

Message Broker

import { messageBroker } from "@uoj-lk/utils-node";

// Connect to a queue
await messageBroker.connectToMessageBroker("QUEUE_NAME");

// Send message to queue
await messageBroker.sendToQueue("QUEUE_NAME", { data: "value" });

// Consume messages
await messageBroker.consumeFromMessageBroker(async (message) => {
  console.log("Received:", message);
}, "QUEUE_NAME");

Logger

import { logger } from "@uoj-lk/utils-node";

logger.info("Message", { data: "value" });
logger.error("Error message", error);
logger.debug("Debug info");

Database Helper

import { dbHelper } from "@uoj-lk/utils-node";

// Setup database with configuration
const sequelize = await dbHelper.setupDatabase(
  {
    database: "myapp",
    username: "root",
    password: "secret",
    host: "localhost",
    port: 3306,
  },
  {
    environment: "production",
    maxRetries: 5,
    retryDelayMs: 5000,
  },
);

// Or create instance and initialize separately
const instance = dbHelper.createSequelizeInstance(config, options);
await dbHelper.initializeDatabase(options);

// Check connection status
const isConnected = dbHelper.isDatabaseConnected();

// Get Sequelize instance
const sequelize = dbHelper.getSequelizeInstance();

// Close connection
await dbHelper.closeDatabase();

Query Helper

import { queryHelper } from "@uoj-lk/utils-node";

// Check if record exists (throws 404 if not found)
await queryHelper.checkRecordExistByAttribute(
  UserModel,
  { email: "[email protected]" },
  "User with this email not found",
);

// Check record does not exist (throws 406 if found)
await queryHelper.checkRecordNotExistByAttribute(
  UserModel,
  { email: "[email protected]" },
  "User with this email already exists",
);

// Check for duplicate during update (throws 406 if different record exists)
await queryHelper.checkRecordNotExistByAttributeForUpdate(
  UserModel,
  userId,
  { email: newEmail },
  "Email already in use by another user",
  { idField: "id" },
);

// Fetch record without throwing (returns null if not found)
const user = await queryHelper.checkRecordExistByAttributeForUpload(UserModel, {
  id: 123,
});

Cache

import { cache } from "@uoj-lk/utils-node";

await cache.initCache();

// Set with 1 hour TTL
await cache.set("key", { data: "value" }, 3600);

// Get value
const value = await cache.get("key");

// Delete key
await cache.del("key");

Error Handling

import { error } from "@uoj-lk/utils-node";

const customError = error.createError("Not found", 404);

const boomError = error.ErrorHelper({
  message: "Validation failed",
  statusCode: 400,
  data: { field: "email" },
});

Validation

import { validation } from "@uoj-lk/utils-node";
import Joi from "joi";

const schema = Joi.object({
  email: Joi.string().email().required(),
  name: Joi.string().required(),
});

// Returns validated and sanitized data directly
const validatedData = await validation.validate(schema, data);

Response Handler

import { response } from "@uoj-lk/utils-node";

const handler = response.createResponseHandler();

// Send success response
handler.resolve(res, { message: "Success" }, 200);

// Send error response
handler.reject(error, res);

Authentication

import { auth } from "@uoj-lk/utils-node";
import express from "express";

const app = express();

// Create middleware for JWT validation
const authMiddleware = auth.authenticateDevJWT(authNodeInstance);

// Apply middleware to routes
app.get("/protected", authMiddleware, (req, res) => {
  // req.user, req.roles, req.permissions are now available
  res.json({ user: req.user, roles: req.roles });
});

// Extract token manually from request
const token = auth.extractTokenFromRequest(req, "accessToken");

Features:

  • Extracts JWT from Authorization header (Bearer) or cookies
  • Validates token using auth service
  • Attaches user data, roles, and permissions to request object
  • Handles missing or invalid tokens with proper error responses
  • Supports custom cookie names

Helpers

import { helpers } from "@uoj-lk/utils-node";

// Convert string to camelCase
helpers.toCamel("hello_world"); // 'helloWorld'

// Pad number with zeros
helpers.padWithZero(5, 3); // '005'

// CSV to JSON
const json = helpers.csvToJson("name,age\nJohn,30");

// Async forEach
await helpers.asyncForEach(array, async (item) => {
  console.log(item);
});

Environment Variables

The package uses these environment variables:

Message Broker

  • RABBIT_MQ_HOST - RabbitMQ host (default: localhost)
  • RABBIT_MQ_PORT - RabbitMQ port (default: 5672)
  • RABBIT_MQ_USERNAME - RabbitMQ username (default: guest)
  • RABBIT_MQ_PASSWORD - RabbitMQ password (default: guest)
  • RABBIT_MQ_VHOST - RabbitMQ virtual host (default: /)

Logger

  • LOG_LEVEL - Log level (default: info)
  • LOG_DIR - Log directory (default: ./logs)
  • NODE_ENV - Environment (default: development)

Cache

  • REDIS_HOST - Redis host (default: localhost)
  • REDIS_PORT - Redis port (default: 6379)
  • REDIS_DB - Redis database (default: 0)
  • REDIS_PASSWORD - Redis password

Database Helper

  • MARIADB_HOST - Database host (default: localhost)
  • MARIADB_PORT - Database port (default: 3306)
  • MARIADB_USER - Database username
  • MARIADB_PASSWORD - Database password
  • MARIADB_DATABASE - Database name
  • NODE_ENV - Environment (controls SQL query logging; disabled in production)

API Documentation

See individual module documentation in src/ directory.

Contributing

Please follow the existing code style and add tests for new features.

License

MIT