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

candour-backend-utils

v1.1.6

Published

Shared utilities for Candour backend microservices

Readme

Candour Backend Utils Library

Shared utilities for Candour backend microservices. This library consolidates common functions used across all microservices to reduce code duplication and improve maintainability.

Installation

npm install candour-backend-utils

Features

  • Date/Time Utilities: Timezone handling, date formatting, date ranges
  • String Utilities: Formatting, validation, token generation
  • HTTP Utilities: Request parsing, pagination, CORS configuration
  • Filesystem Utilities: JSON file operations, directory management
  • Caching Utilities: Redis-based and in-memory caching
  • Validation Utilities: Common validation functions

Usage

Date/Time Utilities

import { 
  getUserTimeZone, 
  formatDateToYearMonthDayTime,
  formatDateToDayMonthYear,
  currentTimestamp 
} from 'candour-backend-utils';

// Get user timezone from request
const timezone = getUserTimeZone(req);

// Format dates
const formatted = formatDateToYearMonthDayTime(new Date(), timezone);
// Output: "13 Dec 2025 02:30:45 PM"

// Get current timestamp in user's timezone
const timestamp = currentTimestamp(req);

String Utilities

import { 
  formatNumberWithCommas,
  generateToken,
  genReference,
  capitalizeFirstLetter 
} from 'candour-backend-utils';

// Format numbers
const formatted = formatNumberWithCommas(1234.567);
// Output: "1,234.56"

// Generate tokens and references
const token = generateToken();
const ref = genReference();

// String manipulation
const capitalized = capitalizeFirstLetter("hello");
// Output: "Hello"

HTTP Utilities

import { 
  pagination,
  getPagination,
  getPublicAddress,
  createCorsOptions 
} from 'candour-backend-utils';

// Get pagination parameters
const { offset, limit, page } = pagination(req);

// Get client IP
const ip = getPublicAddress(req);

// Configure CORS
const corsOptions = createCorsOptions(['http://localhost:3000'], false);

Caching Utilities

import { CacheService, MemoryCache } from 'candour-backend-utils';

// Redis-based caching
const cache = new CacheService('redis://localhost:6379');

// Store value with 1-hour TTL
await cache.set('user:123', userData, 3600);

// Retrieve value
const user = await cache.get('user:123');

// Memoize expensive function
const result = await cache.memoize(
  async () => await fetchExpensiveData(),
  'expensive:data',
  3600
);

// In-memory cache (no Redis required)
const memCache = new MemoryCache();
memCache.set('key', 'value', 60000); // 60 seconds
const value = memCache.get('key');

Validation Utilities

import { 
  isValidUUID,
  isValidEmail,
  isValidPhone,
  isPositiveNumber 
} from 'candour-backend-utils';

// Validate UUID
if (!isValidUUID(id)) {
  throw new Error('Invalid ID format');
}

// Validate email
if (!isValidEmail(email)) {
  throw new Error('Invalid email');
}

// Validate phone
if (!isValidPhone(phone)) {
  throw new Error('Invalid phone number');
}

Filesystem Utilities

import { 
  extractJsonData,
  writeJsonDataToFile,
  createImagesFolder 
} from 'candour-backend-utils';

// Read JSON file
const data = extractJsonData('/path/to/data.json');

// Write JSON file
writeJsonDataToFile('/path/to/output.json', { key: 'value' });

// Create images folder
createImagesFolder();

API Reference

Date/Time

| Function | Description | Returns | |----------|-------------|---------| | getUserTimeZone(req) | Get user timezone from IP | string | | formatDateToYearMonthDayTime(date, timezone) | Format date with time | string \| null | | formatDateToDayMonthYear(date, timezone) | Format date without time | string \| null | | formatDateToDDMMYYYY(date) | Format to DD-MM-YYYY | string | | currentTimestamp(req) | Get current time in user timezone | Date | | getDateRange(start, end) | Get array of dates | string[] | | normalizeDate(date) | Normalize to YYYY-MM-DD | string |

String

| Function | Description | Returns | |----------|-------------|---------| | generateToken() | Generate random token | string | | genReference() | Generate reference ID | string | | generateJobId() | Generate job ID | string | | formatNumberWithCommas(num) | Format number with commas | string | | truncateToTwoDecimals(num) | Truncate to 2 decimals | number | | capitalizeFirstLetter(str) | Capitalize first letter | string | | trimAndLowerCase(str) | Trim and lowercase | string | | removeWhiteSpace(str) | Remove all whitespace | string \| undefined |

HTTP

| Function | Description | Returns | |----------|-------------|---------| | pagination(req) | Get pagination params | { offset, limit, page } | | getPagination(req) | Get validated pagination | { offset, limit, page } | | getPublicAddress(req) | Get client IP | string | | getUserAgentHeader(req) | Get user agent | string \| undefined | | getUpdatedFields(existing, updated) | Get changed fields | Partial<T> | | createCorsOptions(origins, isProd) | Create CORS config | CorsOptions |

Caching

| Class | Method | Description | |-------|--------|-------------| | CacheService | get(key) | Get cached value | | | set(key, value, ttl) | Set cached value | | | del(key) | Delete cached value | | | memoize(fn, key, ttl) | Memoize function | | MemoryCache | get(key) | Get from memory cache | | | set(key, value, ttl) | Set in memory cache | | | clear() | Clear all cache |

Validation

| Function | Description | Returns | |----------|-------------|---------| | isValidUUID(uuid) | Validate UUID format | boolean | | isValidEmail(email) | Validate email format | boolean | | isValidPhone(phone) | Validate phone number | boolean | | isValidCurrencyCode(code) | Validate currency code | boolean | | isPositiveNumber(num) | Check if number > 0 | boolean | | isValidUrl(url) | Validate URL format | boolean |

Migration Guide

Before (Duplicated Code)

// In each microservice
export const formatNumberWithCommas = (input: number | string) => {
  // ... 30 lines of code duplicated across 7 services
};

After (Using Library)

import { formatNumberWithCommas } from 'candour-backend-utils';

// Use directly
const formatted = formatNumberWithCommas(1234.56);

Benefits

  • Reduced Duplication: Eliminated ~2,000+ lines of duplicate code
  • Consistency: Same behavior across all microservices
  • Maintainability: Fix bugs once, deploy everywhere
  • Type Safety: Full TypeScript support
  • Performance: Optimized caching mechanisms

Development

# Install dependencies
npm install

# Build
npm run build

# Test
npm test

Publishing

# Build the library
npm run build

# Publish to npm (private registry)
npm publish

Version History

  • 1.0.0 - Initial release with core utilities from 7 microservices

License

ISC

Support

For issues or questions, please contact the backend team or create an issue in the repository.