lgc-utilities-share
v1.0.2
Published
A comprehensive TypeScript utility library providing common functions for data manipulation, validation, conversion, and more.
Downloads
16
Readme
LGC Utilities Shared
A comprehensive TypeScript utility library providing common functions for data manipulation, validation, conversion, and more.
📑 Table of Contents
- 📦 Installation
- 🚀 Usage
- 🔗 Interfaces
- 📋 Enums
- 🛠️ Helper Functions
- 📚 API Reference
- 🔧 URL Utilities
📦 Installation
npm install lgc-utilities-share🚀 Usage
import { upperFirstLetter, isEqual, deepClone } from 'lgc-utilities-share/utilities';
// or import specific utilities
import upperFirstLetter from 'lgc-utilities-share/utilities/upperFirstLetter';🔗 Interfaces
The library provides TypeScript interfaces for common data structures and API patterns.
Import Interfaces
import {
IFilterRequest,
IPagingResult,
IFilterResponse,
TOrderTuple,
} from 'lgc-utilities-share/interfaces';Available Interfaces
IFilterRequest
Standard interface for API filtering and pagination requests.
interface IFilterRequest {
search_value?: string; // Search term for filtering
page_size?: number; // Number of items per page
page?: number; // Current page number (0-based)
orders?: TOrderTuple[]; // Array of sorting instructions
}IFilterResponse
Response metadata for filtered/paginated API responses.
interface IFilterResponse {
filter: IFilterRequest; // Applied filter parameters
total_count: number; // Total number of items available
}IPagingResult<T>
Generic interface for paginated API responses with typed data.
interface IPagingResult<T> {
page_info: IFilterResponse; // Pagination metadata
data: T[]; // Array of typed data items
}TOrderTuple
Type definition for sorting instructions.
type TOrderTuple = [string, 'ASC' | 'DESC'];📋 Enums
The library provides enums for common error codes and application states.
Import Enums
import { EErrorCode } from 'lgc-utilities-share/enums';Available Enums
EErrorCode
Comprehensive error codes for API responses and error handling.
enum EErrorCode {
// General Errors
DATA_ERROR = 'DATA_ERROR',
INTERNAL_SERVER_ERROR = 'INTERNAL_SERVER_ERROR',
BAD_REQUEST = 'BAD_REQUEST',
// Authentication & Authorization
UNAUTHENTICATED = 'UNAUTHENTICATED', // Server doesn't know who you are
FORBIDDEN = 'FORBIDDEN', // Server knows who you are, but no permission
TOKEN_EXPIRED = 'TOKEN_EXPIRED',
SESSION_EXPIRED = 'SESSION_EXPIRED',
// GraphQL Errors
GRAPHQL_PARSE_FAILED = 'GRAPHQL_PARSE_FAILED',
GRAPHQL_VALIDATION_FAILED = 'GRAPHQL_VALIDATION_FAILED',
BAD_USER_INPUT = 'BAD_USER_INPUT',
}🛠️ Helper Functions
The library provides helper functions for logging and common application utilities.
Import Helpers
import {
logger,
getListLogFile,
getContentLogFile,
ELogType,
} from 'lgc-utilities-share/helper/logger';Logger Helper
Comprehensive logging solution built on Pino with file rotation and pretty printing.
logger
Main logger instance with multiple output streams and structured logging.
Features:
- Console output with pretty formatting
- File rotation by log level (error, debug, fatal, info)
- ISO timestamp formatting
- Safe logging with circular reference handling
ELogType
Enum defining available log types for file operations.
enum ELogType {
INFO = 'info',
ERROR = 'error',
ACCESS = 'access',
FATAL = 'fatal',
}getListLogFile(type: ELogType): Promise<string[]>
Retrieves list of log files for a specific log type.
Input: type: ELogType - The type of logs to retrieve
Output: Promise<string[]> - Array of log filenames
import { getListLogFile, ELogType } from 'lgc-utilities-share/helper/logger';
// Get all error log files
const errorLogs = await getListLogFile(ELogType.ERROR);
console.log(errorLogs); // ['error.20240119', 'error.20240118', ...]
// Get all info log files
const infoLogs = await getListLogFile(ELogType.INFO);
console.log(infoLogs); // ['info.20240119', 'info.20240117', ...]getContentLogFile(type: ELogType, filename: string): Promise<string>
Retrieves the content of a specific log file.
Input:
type: ELogType- The type of log filefilename: string- The specific log filename
Output: Promise<string> - Log file content or 'nil' if not found
import { getContentLogFile, ELogType } from 'lgc-utilities-share/helper/logger';
// Read specific error log file
const logContent = await getContentLogFile(ELogType.ERROR, 'error.20240119');
console.log(logContent);
// Handle missing files
const missingLog = await getContentLogFile(ELogType.INFO, 'nonexistent.log');
console.log(missingLog); // 'nil'Log File Structure:
- Log files are organized by type in separate directories
- Files are automatically rotated based on time intervals
- Error, debug, and fatal logs rotate daily
- Info logs rotate every 2 days
- Files are stored in
logs/[type]/directories
Example Log Output:
[2024-01-19T10:30:45.123Z] INFO: Application started
[2024-01-19T10:30:46.456Z] ERROR: Database connection failed
error: {
"code": "ECONNREFUSED",
"address": "127.0.0.1",
"port": 5432
}📚 API Reference
Common Utilities
Array Utilities
arrayMoveElementByIndex<T>(array, oldIndex, newIndex)
Moves array element from one index to another with negative index support and auto-extension.
Input: array: (T | undefined)[], oldIndex: number, newIndex: number
Output: (T | undefined)[]
arrayMoveElementByIndex([1, 2, 3, 4, 5], 0, 2); // [2, 3, 1, 4, 5]
arrayMoveElementByIndex([1, 2, 3, 4, 5], 2, 0); // [3, 1, 2, 4, 5]checkArrayOverlap<T>(arr1, arr2)
Efficiently checks if two arrays have overlapping elements using Set.
Input: arr1: T[], arr2: T[]
Output: boolean
checkArrayOverlap([1, 2, 3], [4, 5, 6]); // false
checkArrayOverlap([1, 2, 3], [3, 4, 5]); // trueconvertArrToMap<T, R>(arr, keyMapFnc, valueMapFnc)
Converts array to Map using custom key and value mapping functions.
Input: arr: T[], keyMapFnc: (item: T) => T[keyof T], valueMapFnc: (item: T) => R
Output: Map<T[keyof T], R>
convertArrToMap(
[
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
],
(item) => item.id,
(item) => item.name
); // Map { 1 => 'John', 2 => 'Jane' }generateRangeArray(start, end)
Generates array of consecutive integers within specified range.
Input: start: number, end: number
Output: number[]
generateRangeArray(1, 5); // [1, 2, 3, 4, 5]
generateRangeArray(5, 1); // []getValidArray<T>(array?)
Ensures value is valid array, returns empty array for invalid inputs.
Input: array: T[] | undefined
Output: T[]
getValidArray(); // []
getValidArray([1, 2, 3]); // [1, 2, 3]
getValidArray(null); // []groupElementByKey<T, K>(items, keyExtractor)
Groups array elements by specified key using extractor function.
Input: items: T[], keyExtractor: (item: T) => K | undefined
Output: Record<K, T[]>
groupElementByKey(
[
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 1, name: 'Jim' },
],
(item) => item.id
); // {1: [{id: 1, name: 'John'}, {id: 1, name: 'Jim'}], 2: [{id: 2, name: 'Jane'}]}paginate<T>(items, filter?)
Paginates array with comprehensive page info and filter support.
Defaults: page = 0 (0-based), page_size = 10
Input: items: T[], filter?: IFilterRequest
Output: IPagingResult<T>
// Defaults applied
paginate([1, 2, 3, 4, 5]);
// { data: [1, 2, 3, 4, 5], page_info: { filter: { page: 0, page_size: 10 }, total_count: 5 } }
// Override page_size only
paginate([1, 2, 3, 4, 5], { page_size: 2 });
// { data: [1, 2], page_info: { filter: { page: 0, page_size: 2 }, total_count: 5 } }
// Explicit page and page_size
paginate([1, 2, 3, 4, 5], { page: 1, page_size: 2 });
// { data: [3, 4], page_info: { filter: { page: 1, page_size: 2 }, total_count: 5 } }uniqBy<T, K>(array, keySelector)
Removes duplicates from array based on key selector function.
Input: array: T[], keySelector: (item: T) => K
Output: T[]
uniqBy(
[
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 1, name: 'John' },
],
(item) => item.id
);
// [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]Object Utilities
deepClone<T>(object, weakMap)
Creates deep clone handling various data types and circular references.
Input: object: T, weakMap: WeakMap<any, any> | undefined
Output: T
deepClone({ a: 1, b: { c: 2 } }); // {a: 1, b: {c: 2}}
deepClone([{ x: 1 }, { y: 2 }]); // [{x: 1}, {y: 2}]get<T>(object, path, defaultValue)
Gets value from object using dot-notation path with fallback.
Input: object: any, path: string, defaultValue: T | undefined
Output: T
get({ a: 1, b: { c: 2 } }, 'a'); // 1
get({ a: 1, b: { c: 2 } }, 'b.c'); // 2
get({ a: 1, b: { c: 2 } }, 'c', 3); // 3isEmptyObject<T>(object)
Checks if object is empty, handles null/undefined and non-objects.
Input: object: T
Output: boolean
isEmptyObject({}); // true
isEmptyObject({ a: 1 }); // false
isEmptyObject(null); // trueisEqual<T>(object1, object2, seen?)
Deep equality comparison for objects, arrays, Date, RegExp, with NaN equality and circular reference handling via pair-tracking.
Input: object1: T, object2: T, seen?: WeakMap<object, WeakSet<object>>
Output: boolean
isEqual({ a: 1, b: 2 }, { a: 1, b: 2 }); // true
isEqual({ a: 1, b: 2 }, { a: 1, b: 3 }); // false
isEqual(new Date('2021-01-01'), new Date('2021-01-01')); // true
isEqual(NaN, NaN); // truepickByWithCondition<T>(obj, predicate)
Picks object properties based on predicate condition.
Input: obj: T, predicate: (value: T[keyof T], key: keyof T) => boolean
Output: Partial<T>
pickByWithCondition({ a: 1, b: 2, c: 3 }, (value, key) => value > 1); // { b: 2, c: 3 }pickNestedProperty<T, Y>(object, path, defaultValue?)
Picks nested property using dot notation with type safety.
Input: object: Record<string, any>, path: string, defaultValue?: Y
Output: T | Y | undefined
pickNestedProperty({ a: { b: 1 } }, 'a.b'); // 1
pickNestedProperty({ a: { b: 1 } }, 'a.c', 2); // 2trimData<T>(data)
Recursively trims strings in nested objects/arrays preserving structure.
Input: data: T
Output: TrimmedData<T>
trimData({ name: ' John ', items: [' item1 ', ' item2 '] });
// { name: 'John', items: ['item1', 'item2'] }trimKeys<T>(object, keys)
Removes specified keys from object without mutation.
Input: object: T, keys: string[]
Output: T
trimKeys({ a: 1, b: 2, c: 3 }, ['a', 'b']); // { c: 3 }String Utilities
startCase(input)
Converts string to start case, handles underscores and capitalization.
Input: input: string
Output: string
startCase('hello_world'); // 'Hello World'
startCase('test'); // 'Test'toLowerCaseNonAccentVietnamese(str)
Converts Vietnamese text to lowercase without accents for search.
Input: str: string
Output: string
toLowerCaseNonAccentVietnamese('Nguyễn Văn Đức'); // 'nguyen van duc'toNonAccentVietnamese(str)
Removes Vietnamese accents while preserving original case.
Input: str: string
Output: string
toNonAccentVietnamese('Nguyễn Văn Đức'); // 'Nguyen Van Duc'upperFirstLetter(str)
Converts first letter to uppercase with safe empty string handling.
Input: str: string | undefined
Output: string
upperFirstLetter('test'); // 'Test'
upperFirstLetter('TEST'); // 'TEST'
upperFirstLetter(''); // ''Validation Utilities
checkFalsy<T>(value)
Checks if value is falsy including empty arrays and objects.
Input: value: T
Output: boolean
checkFalsy(null); // true
checkFalsy([]); // true
checkFalsy({}); // true
checkFalsy('hello'); // falsecheckJSONText<T>(text)
Validates if string is valid JSON with type safety.
Input: text: T
Output: boolean
checkJSONText('{"name": "John", "age": 30}'); // true
checkJSONText('{"name": "John", "age": 30'); // false
checkJSONText(123); // falseisEmpty<T>(value)
Checks if a value is empty or considered "empty" based on its type. Supports comprehensive type checking including primitives, collections, and objects with whitespace-only string handling.
Input: value: T - The value to check for emptiness
Output: boolean - Returns true if the value is empty, false otherwise
// Primitive types
isEmpty(null); // true
isEmpty(undefined); // true
isEmpty(''); // true
isEmpty(' '); // true (whitespace-only strings)
// Numbers and other primitives
isEmpty(0); // false
isEmpty(42); // false
isEmpty(NaN); // true (NaN is considered empty)
isEmpty(false); // false
isEmpty(Symbol()); // false
isEmpty(BigInt(0)); // false
// Collections
isEmpty([]); // true
isEmpty([1, 2, 3]); // false
isEmpty({}); // true
isEmpty({ key: 'value' }); // false
isEmpty(new Map()); // true
isEmpty(new Set()); // true
// Dates and other objects
isEmpty(new Date()); // false
isEmpty(/pattern/); // false
isEmpty(() => {}); // falseisNullish<T>(value)
Checks if value is null or undefined with proper TypeScript typing.
Input: value: T | null | undefined
Output: boolean
isNullish(null); // true
isNullish(undefined); // true
isNullish(0); // falseisValidUrl(url)
Validates URL format using native URL constructor.
Input: url: string
Output: boolean
isValidUrl('https://example.com'); // true
isValidUrl('example.com'); // false
isValidUrl('http://example.com'); // truesearchByKey(searchContent, content)
Case-insensitive search with Vietnamese accent normalization.
Input: searchContent: string, content: string
Output: boolean
searchByKey('test', 'This is a Test'); // true
searchByKey('nguyễn', 'Nguyễn Văn A'); // truevalidateDateRange(targetDate, startDate?, endDate?, allowSame?)
Validates if date falls within range with configurable boundaries.
Input: targetDate: Date, startDate?: Date | null, endDate?: Date | null, allowSame?: boolean
Output: boolean
validateDateRange(new Date('2023-06-15'), new Date('2023-06-01'), new Date('2023-06-30')); // true
validateDateRange(new Date('2023-07-01'), new Date('2023-06-01'), new Date('2023-06-30')); // falsevalidateTimeString(timeStr, pattern?)
Validates time string format using customizable regex patterns.
Input: timeStr: string, pattern?: RegExp
Output: boolean
validateTimeString('12:30'); // true
validateTimeString('25:00'); // false
validateTimeString('12:60'); // falseDate & Time Utilities
calculateTimeDiff(startDate, endDate)
Calculates time difference in days, hours, minutes, and seconds.
Input: startDate: Date, endDate: Date
Output: { days: number; hours: number; minutes: number; seconds: number }
calculateTimeDiff(new Date('2021-01-01'), new Date('2021-01-02'));
// { days: 1, hours: 0, minutes: 0, seconds: 0 }checkOverlapTime<T>(range1, range2)
Checks if two time ranges overlap with proper date comparison.
Input: range1: T extends [Date, Date], range2: T extends [Date, Date]
Output: boolean
checkOverlapTime(
[new Date('2021-01-01'), new Date('2021-01-02')],
[new Date('2021-01-02'), new Date('2021-01-03')]
); // truegetUTCDateRangeMoment(value, timezone)
Converts zoned dates to UTC date range moments for consistency.
Input: value: TZonedDateInput | [TZonedDateInput, TZonedDateInput], timezone: string
Output: [Moment, Moment]
getUTCDateRangeMoment('2021-01-01', 'America/New_York');
// [Moment (start of day UTC), Moment (end of day UTC)]Number Utilities
roundToTwoDecimals(num)
Rounds number to two decimal places with floating-point handling.
Input: num: number
Output: number
roundToTwoDecimals(1.2345); // 1.23
roundToTwoDecimals(1.236); // 1.24toFixedNumber(num, digits, base?)
Rounds number to specified decimal places with configurable base.
Input: num: number, digits: number, base?: number
Output: number
toFixedNumber(1.2345, 2); // 1.23
toFixedNumber(1.2345, 2, 2); // 1.25Generator Utilities
generateRandomPassword(options)
Generates secure random password with customizable character sets.
Input: options: { length?: number; includeUppercase?: boolean; includeNumbers?: boolean; includeSpecialChars?: boolean }
Output: string
generateRandomPassword(); // 'aBc123!@#$%^'
generateRandomPassword({ length: 8, includeSpecialChars: false }); // 'aBc12345'generateRelatedId(id, prefix)
Generates related ID by concatenating prefix and ID.
Input: id: string, prefix: string
Output: string
generateRelatedId('123', 'user'); // 'user_123'generateUniqueNumber()
Generates unique number based on timestamp and random value.
Input: void
Output: number
generateUniqueNumber(); // 1640995200123456Geographic Utilities
convertToDMS(lat, lng)
Converts coordinates to DMS (Degrees, Minutes, Seconds) format.
Input: lat: number, lng: number
Output: string
convertToDMS(12.345678, 123.456789); // "12°20'44.4"N 123°27'24.4"E"
convertToDMS(-12.345678, -123.456789); // "12°20'44.4"S 123°27'24.4"W"Async Utilities
sleep(ms)
Creates promise that resolves after specified milliseconds.
Input: ms: number
Output: Promise<unknown>
await sleep(1000); // Sleeps for 1 second
await sleep(-100); // Sleeps for 500 milliseconds (fallback)Converter Utilities
convertMToKm(meters, options?)
Converts meters to kilometers with flexible precision and rounding.
Input: meters: number, options?: ConvertMToKmOptions
Output: number | undefined
convertMToKm(1500); // 1.5
convertMToKm(1234, { precision: 3 }); // 1.234
convertMToKm(1500, { roundingMethod: 'ceil' }); // 2convertToRawString(str)
Converts string to raw string by removing non-alphanumeric characters.
Input: str: string
Output: string
convertToRawString('[email protected]'); // 'testexamplecom'
convertToRawString('Hello World!'); // 'HelloWorld'
convertToRawString('$19.99'); // '1999'convertUTCDateToZonedMoment(date, timezone)
Converts UTC date to moment in specific timezone.
Input: date: Date | string, timezone: string
Output: Moment
convertUTCDateToZonedMoment(new Date(), 'Asia/Ho_Chi_Minh');
// Returns: Moment in Vietnam timezoneconvertZonedDateToUTCMoment(date, timezone)
Converts zoned date to UTC moment.
Input: date: Date | string, timezone: string
Output: Moment
convertZonedDateToUTCMoment('2024-01-19 14:00:00', 'Asia/Ho_Chi_Minh');
// Returns: Moment in UTCOther Utilities
executeCallbacks(callbacks, initialData)
Executes multiple callback functions in parallel with shared data.
Input: callbacks: TMixedFunction[], initialData: any
Output: Promise<void>
await executeCallbacks(
[
(data) => console.log('Callback 1:', data),
async (data) => {
await sleep(100);
console.log('Callback 2:', data);
},
],
'shared data'
);wrapInPipeline
Wraps functions in pipeline where output becomes next input.
Input: fns: TMixedFunction[]
Output: TMixedFunction
const pipeline = wrapInPipeline([(x) => x * 2, (x) => x + 1, (x) => x.toString()]);
await pipeline(5); // "11"genCode
Generates unique code with prefix, timestamp, and random characters.
Input: prefix: string
Output: string
genCode('USER'); // 'USER-2401191234ABCD'Version Utilities
getBuildVersion
Gets current build version from environment or version file.
Input: void
Output: string
getBuildVersionFromFile
Reads build version from .version file or package.json.
Input: void
Output: string
loadBuildVersion
Loads and sets build version in environment variables.
Input: void
Output: void
🔧 URL Utilities
formatUrl
Formats URL ensuring protocol and removing duplicate slashes.
Input: url: string
Output: string | undefined
formatUrl('https://example.com'); // 'https://example.com'
formatUrl('example.com'); // 'https://example.com'
formatUrl('//example.com'); // 'https://example.com'