Skip to main content
Version: 0.5.0 (Previous)

🔧 Common Utilities

The Nodeblocks SDK provides general-purpose utility functions for common operations. These utilities handle basic tasks like UUID generation and type checking that are frequently used across applications.


🎯 Overview

Common utilities provide essential helper functions for everyday programming tasks. They focus on simplicity and reliability for common operations.

Key Features

  • UUID Generation: Reliable UUID v4 generation
  • Type Checking: Object type validation
  • Cross-Platform: Works consistently across different environments
  • Lightweight: Minimal dependencies and overhead

🆔 UUID Generation

generateUUID

Generates a UUID v4 string for unique identifiers.

import { utils } from '@nodeblocks/backend-sdk';

const { generateUUID } = utils;

const id = generateUUID();
// Returns: "550e8400-e29b-41d4-a716-446655440000"

Usage Examples

import { utils } from '@nodeblocks/backend-sdk';

const { generateUUID } = utils;

// Generate unique IDs
const userId = generateUUID();
const sessionId = generateUUID();
const requestId = generateUUID();

// Use in objects
const user = {
id: generateUUID(),
name: 'John Doe',
email: 'john@example.com'
};

// Generate multiple IDs
const ids = Array.from({ length: 5 }, () => generateUUID());

Integration with Entity Utilities

import { utils } from '@nodeblocks/backend-sdk';

const { generateUUID, createBaseEntity } = utils;

// Custom entity creation with additional UUID fields
const createOrder = (orderData: OrderData) => {
const baseEntity = createBaseEntity(orderData);

return {
...baseEntity,
orderNumber: generateUUID(), // Additional UUID field
trackingId: generateUUID() // Another UUID field
};
};

🔍 Type Checking

isObject

Checks if a value is an object type (including functions).

import { utils } from '@nodeblocks/backend-sdk';

const { isObject } = utils;

// Object checks
isObject({}); // true
isObject([]); // true
isObject(() => {}); // true
isObject(null); // false
isObject(undefined); // false
isObject('string'); // false
isObject(123); // false
isObject(true); // false

Usage Examples

import { utils } from '@nodeblocks/backend-sdk';

const { isObject } = utils;

// Validate function parameters
const processData = (data: unknown) => {
if (!isObject(data)) {
throw new Error('Data must be an object');
}

// TypeScript now knows data is an object
return Object.keys(data);
};

// Safe object operations
const safeMerge = (target: unknown, source: unknown) => {
if (!isObject(target) || !isObject(source)) {
return target;
}

return { ...target, ...source };
};

// Conditional processing
const processValue = (value: unknown) => {
if (isObject(value)) {
// Handle object
return JSON.stringify(value);
} else {
// Handle primitive
return String(value);
}
};

🔧 Advanced Usage

Custom Type Guards

import { utils } from '@nodeblocks/backend-sdk';

const { isObject } = utils;

// Build custom type guards
const isUserObject = (value: unknown): value is User => {
return isObject(value) &&
'id' in value &&
'name' in value &&
'email' in value;
};

const isProductObject = (value: unknown): value is Product => {
return isObject(value) &&
'id' in value &&
'name' in value &&
'price' in value;
};

// Usage
const validateUser = (data: unknown) => {
if (!isUserObject(data)) {
throw new Error('Invalid user data');
}

// TypeScript knows data is User type
return data.name;
};

UUID Utilities

import { utils } from '@nodeblocks/backend-sdk';

const { generateUUID } = utils;

// UUID validation
const isValidUUID = (uuid: string): boolean => {
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
return uuidRegex.test(uuid);
};

// Generate UUID with prefix
const generatePrefixedUUID = (prefix: string): string => {
return `${prefix}-${generateUUID()}`;
};

// Generate short UUID (first 8 characters)
const generateShortUUID = (): string => {
return generateUUID().split('-')[0];
};

// Usage
const orderId = generatePrefixedUUID('order'); // "order-550e8400-e29b-41d4-a716-446655440000"
const shortId = generateShortUUID(); // "550e8400"

Object Utilities

import { utils } from '@nodeblocks/backend-sdk';

const { isObject } = utils;

// Deep object validation
const isDeepObject = (value: unknown): boolean => {
if (!isObject(value)) return false;

// Check if all values are also objects or primitives
return Object.values(value).every(val =>
isObject(val) || typeof val === 'string' || typeof val === 'number' || typeof val === 'boolean'
);
};

// Safe object access
const safeGet = (obj: unknown, path: string): unknown => {
if (!isObject(obj)) return undefined;

return path.split('.').reduce((current, key) => {
return isObject(current) ? current[key] : undefined;
}, obj);
};

// Usage
const data = { user: { profile: { name: 'John' } } };
const userName = safeGet(data, 'user.profile.name'); // "John"
const invalid = safeGet(data, 'user.profile.age'); // undefined

📊 Performance Considerations

UUID Generation

  • Performance: UUID generation is fast and efficient
  • Uniqueness: Extremely low collision probability
  • Distribution: Well-distributed across the UUID space

Type Checking

  • Performance: isObject is optimized for speed
  • Accuracy: Handles edge cases like null and undefined
  • Compatibility: Works with arrays and functions

📐️ Best Practices

1. Consistent UUID Usage

// ✅ Good: Use generateUUID for all unique identifiers
const userId = generateUUID();
const orderId = generateUUID();
const sessionId = generateUUID();

// ❌ Avoid: Mixing different ID generation methods
const userId = generateUUID();
const orderId = Date.now().toString(); // Inconsistent

2. Type Safety with isObject

// ✅ Good: Use isObject for type guards
const processData = (data: unknown) => {
if (!isObject(data)) {
throw new Error('Expected object');
}
// TypeScript knows data is an object
return Object.keys(data);
};

// ❌ Avoid: Direct type assertions
const processData = (data: unknown) => {
const obj = data as object; // Unsafe
return Object.keys(obj);
};

3. Error Handling

// ✅ Good: Proper error handling
const safeProcess = (data: unknown) => {
try {
if (!isObject(data)) {
return { error: 'Invalid data type' };
}
return { success: true, data };
} catch (error) {
return { error: 'Processing failed' };
}
};

🔗 See Also