candour-backend-utils
v1.1.6
Published
Shared utilities for Candour backend microservices
Maintainers
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-utilsFeatures
- 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 testPublishing
# Build the library
npm run build
# Publish to npm (private registry)
npm publishVersion 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.
