Utilities
Core Utilities
Discover utility functions and helpers provided by the OMX Core SDK for common development tasks.
Utility Functions
The OMX Core SDK includes a comprehensive set of utility functions and helpers to streamline common development tasks, data validation, formatting, and integration workflows.
Data Validation
Built-in validators for common data types and formats:
import { validators } from '@omx-sdk/core/utils';
// Email validation
const isValidEmail = validators.email('user@example.com');
console.log(isValidEmail); // true
// Phone number validation
const isValidPhone = validators.phone('+1-555-123-4567');
console.log(isValidPhone); // true
// Coordinate validation
const isValidCoordinate = validators.coordinate({
lat: 40.7128,
lng: -74.0060
});
console.log(isValidCoordinate); // true
// Custom validation schema
const userSchema = validators.schema({
email: validators.email(),
phone: validators.phone({ required: false }),
location: validators.coordinate(),
age: validators.number({ min: 18, max: 120 })
});
const user = {
email: 'user@example.com',
location: { lat: 40.7128, lng: -74.0060 },
age: 25
};
const validation = userSchema.validate(user);
if (!validation.valid) {
console.error('Validation errors:', validation.errors);
}Date and Time Utilities
Work with dates, times, and timezones easily:
import { datetime } from '@omx-sdk/core/utils';
// Current timestamp
const now = datetime.now();
console.log(now); // Unix timestamp
// Format dates
const formatted = datetime.format(now, 'YYYY-MM-DD HH:mm:ss');
console.log(formatted); // "2024-01-15 10:30:00"
// Parse dates
const parsed = datetime.parse('2024-01-15T10:30:00Z');
console.log(parsed); // Date object
// Timezone conversion
const utc = datetime.toUTC(new Date());
const local = datetime.toLocal(utc, 'America/New_York');
// Relative time
const relative = datetime.relative(datetime.parse('2024-01-14'));
console.log(relative); // "1 day ago"
// Date math
const tomorrow = datetime.add(now, 1, 'day');
const nextWeek = datetime.add(now, 1, 'week');
const lastMonth = datetime.subtract(now, 1, 'month');
// Business hours checking
const isBusinessHours = datetime.isBusinessHours(now, {
timezone: 'America/New_York',
start: '09:00',
end: '17:00',
weekdays: [1, 2, 3, 4, 5] // Monday to Friday
});Geographic Utilities
Geographic calculations and coordinate transformations:
import { geo } from '@omx-sdk/core/utils';
// Distance calculation
const distance = geo.distance(
{ lat: 40.7128, lng: -74.0060 }, // New York
{ lat: 34.0522, lng: -118.2437 } // Los Angeles
);
console.log(distance); // Distance in meters
// Check if point is within radius
const isWithinRadius = geo.isWithinRadius(
{ lat: 40.7128, lng: -74.0060 }, // Center point
{ lat: 40.7580, lng: -73.9855 }, // Test point
5000 // 5km radius
);
// Bounding box calculation
const boundingBox = geo.boundingBox(
{ lat: 40.7128, lng: -74.0060 },
1000 // 1km radius
);
console.log(boundingBox);
// { north: 40.721, south: 40.704, east: -74.002, west: -74.010 }
// Point in polygon check
const polygon = [
{ lat: 40.7128, lng: -74.0060 },
{ lat: 40.7580, lng: -73.9855 },
{ lat: 40.7282, lng: -73.7949 },
{ lat: 40.6892, lng: -74.0445 }
];
const isInside = geo.pointInPolygon(
{ lat: 40.7300, lng: -74.0000 },
polygon
);
// Coordinate formatting
const dms = geo.toDMS(40.7128, -74.0060);
console.log(dms); // "40°42'46.1"N 74°0'21.6"W"
// Geohash encoding/decoding
const geohash = geo.encode(40.7128, -74.0060, 9);
const decoded = geo.decode(geohash);String and Text Utilities
String manipulation and text processing functions:
import { text } from '@omx-sdk/core/utils';
// Case conversion
const camelCase = text.toCamelCase('hello world');
const snakeCase = text.toSnakeCase('HelloWorld');
const kebabCase = text.toKebabCase('Hello World');
const titleCase = text.toTitleCase('hello world');
// String validation
const isEmail = text.isEmail('user@example.com');
const isUrl = text.isUrl('https://example.com');
const isPhone = text.isPhone('+1-555-123-4567');
// Text processing
const slug = text.slugify('Hello World! How are you?');
// Result: "hello-world-how-are-you"
const excerpt = text.excerpt('This is a long text...', 50);
// Result: "This is a long text..."
const words = text.wordCount('Hello world, how are you?');
// Result: 5
// Template processing
const template = 'Hello {{name}}, welcome to {{app}}!';
const rendered = text.template(template, {
name: 'John',
app: 'OMX Platform'
});
// Result: "Hello John, welcome to OMX Platform!"
// Text sanitization
const sanitized = text.sanitize('<script>alert("xss")</script>Hello');
// Result: "Hello"
// Phone number formatting
const formatted = text.formatPhone('+15551234567', 'US');
// Result: "(555) 123-4567"Object and Array Utilities
Work with objects and arrays more efficiently:
import { collections } from '@omx-sdk/core/utils';
// Deep object operations
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { b: { d: 3 }, e: 4 };
const merged = collections.deepMerge(obj1, obj2);
// Result: { a: 1, b: { c: 2, d: 3 }, e: 4 }
const cloned = collections.deepClone(obj1);
const isEqual = collections.deepEqual(obj1, cloned);
// Object path operations
const value = collections.get(obj1, 'b.c'); // 2
collections.set(obj1, 'b.f', 5);
const hasPath = collections.has(obj1, 'b.c'); // true
// Array utilities
const items = [1, 2, 3, 2, 4, 2];
const unique = collections.unique(items); // [1, 2, 3, 4]
const grouped = collections.groupBy(users, 'department');
const sorted = collections.sortBy(users, 'createdAt');
// Pagination
const paginated = collections.paginate(items, {
page: 2,
limit: 10
});
// Array chunking
const chunks = collections.chunk(items, 2);
// Result: [[1, 2], [3, 2], [4, 2]]
// Filtering utilities
const filtered = collections.filter(users, {
status: 'active',
role: ['admin', 'user']
});
// Data transformation
const mapped = collections.map(users, user => ({
id: user.id,
name: user.firstName + ' ' + user.lastName,
email: user.email
}));Encryption and Hashing
Security utilities for encryption and data integrity:
import { crypto } from '@omx-sdk/core/utils';
// Generate secure random values
const randomString = crypto.randomString(32);
const randomBytes = crypto.randomBytes(16);
const uuid = crypto.uuid();
// Hashing
const md5Hash = crypto.md5('hello world');
const sha256Hash = crypto.sha256('hello world');
const bcryptHash = await crypto.bcrypt('password123');
// Encryption/Decryption
const encrypted = crypto.encrypt('sensitive data', 'encryption-key');
const decrypted = crypto.decrypt(encrypted, 'encryption-key');
// HMAC signing
const signature = crypto.hmac('message', 'secret-key');
const isValid = crypto.verifyHmac('message', signature, 'secret-key');
// JWT utilities
const token = crypto.jwt.sign(
{ userId: '123', role: 'user' },
'secret-key',
{ expiresIn: '1h' }
);
const decoded = crypto.jwt.verify(token, 'secret-key');
// Base64 encoding/decoding
const encoded = crypto.base64Encode('hello world');
const decoded64 = crypto.base64Decode(encoded);HTTP and URL Utilities
HTTP request helpers and URL manipulation:
import { http } from '@omx-sdk/core/utils';
// URL building
const url = http.buildUrl('https://api.example.com', '/users', {
page: 1,
limit: 10,
filter: 'active'
});
// Result: "https://api.example.com/users?page=1&limit=10&filter=active"
// Query string handling
const parsed = http.parseQuery('?page=1&limit=10');
const stringified = http.stringifyQuery({ page: 1, limit: 10 });
// URL validation and parsing
const isValidUrl = http.isValidUrl('https://example.com');
const urlParts = http.parseUrl('https://api.example.com:443/v1/users?page=1');
// HTTP status helpers
const isSuccessStatus = http.isSuccess(200); // true
const isErrorStatus = http.isError(404); // true
const isRedirectStatus = http.isRedirect(301); // true
// Content type helpers
const isJson = http.isJsonContent('application/json');
const isFormData = http.isFormContent('multipart/form-data');
// Request helpers
const headers = http.buildHeaders({
authorization: 'Bearer token',
contentType: 'application/json'
});
// Response helpers
const responseSize = http.getResponseSize(response);
const contentType = http.getContentType(response);Error Handling Utilities
Enhanced error handling and debugging tools:
import { errors } from '@omx-sdk/core/utils';
// Custom error classes
class ValidationError extends errors.BaseError {
constructor(message, field) {
super(message, 'VALIDATION_ERROR');
this.field = field;
}
}
// Error wrapping
const wrappedError = errors.wrap(originalError, 'API_ERROR', {
context: 'user creation',
userId: '123'
});
// Error aggregation
const aggregated = errors.aggregate([
new ValidationError('Invalid email', 'email'),
new ValidationError('Invalid phone', 'phone')
]);
// Retry with exponential backoff
const result = await errors.retry(async () => {
return await riskyOperation();
}, {
maxRetries: 3,
initialDelay: 1000,
backoffMultiplier: 2
});
// Error reporting
errors.report(error, {
userId: '123',
operation: 'create_geotrigger',
metadata: { triggerId: 'trigger_456' }
});
// Stack trace cleaning
const cleanStack = errors.cleanStackTrace(error.stack);
// Error serialization
const serialized = errors.serialize(error);
const deserialized = errors.deserialize(serialized);Performance Utilities
Tools for performance monitoring and optimization:
import { performance } from '@omx-sdk/core/utils';
// Timing measurements
const timer = performance.timer();
await someOperation();
const elapsed = timer.stop();
console.log(`Operation took ${elapsed}ms`);
// Memory usage
const memoryUsage = performance.getMemoryUsage();
console.log('Memory usage:', memoryUsage);
// Debouncing and throttling
const debouncedFn = performance.debounce(expensiveFunction, 300);
const throttledFn = performance.throttle(apiCall, 1000);
// Memoization
const memoizedFn = performance.memoize(expensiveCalculation, {
maxSize: 100,
ttl: 300000 // 5 minutes
});
// Performance monitoring
const monitor = performance.monitor('api_calls');
monitor.start();
await apiCall();
monitor.end();
// Benchmark utilities
const benchmark = performance.benchmark('string_operations', () => {
// Code to benchmark
return 'hello'.repeat(1000);
});
console.log(`Benchmark result: ${benchmark.opsPerSecond} ops/sec`);Best Practices
- Import Specific Functions: Only import utilities you need to reduce bundle size
- Error Handling: Use appropriate error handling utilities for better debugging
- Performance: Use memoization and debouncing for expensive operations
- Validation: Always validate input data before processing
- Security: Use crypto utilities for sensitive data operations
- Testing: Utilities are well-tested - leverage them instead of rolling your own