Uuid
The Uuid class provides universally unique identifiers (UUIDs) with support for UUID v4 (random) and UUID v7 (time-ordered) generation.
Import:
import { Uuid } from 'surrealdb';
Source: value/uuid.ts
Constructor
new Uuid(value)
Create a UUID from an existing value.
Syntax
new Uuid(uuid)
new Uuid(string)
new Uuid(bytes)
Parameters
| Parameter | Type | Description |
|---|
value required | Uuid | string | ArrayBuffer | Uint8Array | Value to create UUID from. |
Examples
const uuid = new Uuid('550e8400-e29b-41d4-a716-446655440000');
const bytes = new Uint8Array([]);
const uuid = new Uuid(bytes);
const copy = new Uuid(uuid);
Static Methods
Uuid.v4()
Generate a random UUID v4.
Syntax
Uuid.v4()
Returns
Uuid - Random UUID v4
Example
const randomId = Uuid.v4();
console.log(randomId.toString());
const userId = new RecordId('users', Uuid.v4());
await db.create(userId).content(userData);
Uuid.v7()
Generate a time-ordered UUID v7.
Syntax
Uuid.v7()
Returns
Uuid - Time-ordered UUID v7
UUID v7 includes a timestamp component, making it sortable by creation time. This is useful for time-series data and maintaining chronological order.
Example
const timeOrderedId = Uuid.v7();
const id1 = Uuid.v7();
const id2 = Uuid.v7();
Uuid.parse(string)
Parse a UUID from its string representation.
Syntax
Uuid.parse(str)
Parameters
| Parameter | Type | Description |
|---|
str required | string | UUID string in standard format. |
Returns
Uuid - Parsed UUID
Example
const uuid = Uuid.parse('550e8400-e29b-41d4-a716-446655440000');
Instance Methods
.toString()
Convert to string representation.
Syntax
uuid.toString()
Returns
string - UUID string in standard format (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
Example
const uuid = Uuid.v4();
console.log(uuid.toString());
.toJSON()
Serialize for JSON.
Syntax
uuid.toJSON()
Returns
string - UUID string
.toUint8Array()
Get the binary representation as Uint8Array.
Syntax
uuid.toUint8Array()
Returns
Uint8Array - 16-byte binary representation
Example
const uuid = Uuid.v4();
const bytes = uuid.toUint8Array();
console.log(bytes.length);
.toBuffer()
Get the binary representation as ArrayBuffer.
Syntax
uuid.toBuffer()
Returns
ArrayBufferLike - Binary representation
.equals(other)
Check if two UUIDs are equal.
Syntax
uuid.equals(other)
Returns
boolean - True if equal
Complete Examples
Session Management
import { Surreal, Uuid, RecordId, DateTime, Duration, Table } from 'surrealdb';
const db = new Surreal();
await db.connect('ws://localhost:8000');
const sessionId = Uuid.v4();
const session = await db.create(new RecordId('sessions', sessionId))
.content({
user: userId,
created_at: DateTime.now(),
expires_at: DateTime.now().plus(Duration.parse('24h')),
ip_address: '192.168.1.1'
});
console.log('Session ID:', sessionId.toString());
Time-Ordered Records
const events = [];
for (let i = 0; i < 100; i++) {
const eventId = Uuid.v7();
await db.create(new RecordId('events', eventId)).content({
type: 'user_action',
timestamp: DateTime.now(),
data: { action: 'click', target: 'button' }
});
events.push(eventId);
}
Unique Identifiers
const requestId = Uuid.v4();
const correlationId = Uuid.v4();
const traceId = Uuid.v7();
await db.create(new Table('requests')).content({
id: requestId,
correlation_id: correlationId,
trace_id: traceId,
timestamp: DateTime.now()
});
API Keys
function generateApiKey(): string {
return `api_${Uuid.v4().toString().replace(/-/g, '')}`;
}
const apiKey = generateApiKey();
console.log(apiKey);
await db.create(new Table('api_keys')).content({
key: apiKey,
user: userId,
created_at: DateTime.now()
});
Distributed System IDs
class IdGenerator {
static generateOrderId(): Uuid {
return Uuid.v7();
}
static generateTransactionId(): Uuid {
return Uuid.v7();
}
static generateRandomId(): Uuid {
return Uuid.v4();
}
}
const orderId = IdGenerator.generateOrderId();
const txnId = IdGenerator.generateTransactionId();
File Upload Tracking
async function uploadFile(file: File): Promise<string> {
const uploadId = Uuid.v4();
await db.create(new RecordId('uploads', uploadId)).content({
filename: file.name,
size: file.size,
mime_type: file.type,
uploaded_at: DateTime.now(),
status: 'processing'
});
return uploadId.toString();
}
Parsing and Validation
function validateUuid(input: string): Uuid | null {
try {
return Uuid.parse(input);
} catch (error) {
console.error('Invalid UUID format');
return null;
}
}
const userInput = '550e8400-e29b-41d4-a716-446655440000';
const uuid = validateUuid(userInput);
if (uuid) {
const record = await db.select(new RecordId('items', uuid));
}
Batch ID Generation
function generateBatchIds(count: number, useV7 = false): Uuid[] {
const ids: Uuid[] = [];
for (let i = 0; i < count; i++) {
ids.push(useV7 ? Uuid.v7() : Uuid.v4());
}
return ids;
}
const randomIds = generateBatchIds(100);
const sortableIds = generateBatchIds(100, true);
UUID v4 vs UUID v7
UUID v4 (Random)
- Pros: Truly random, no predictability
- Cons: Not sortable, no time information
- Use when: You need unpredictable, secure IDs
const randomId = Uuid.v4();
UUID v7 (Time-ordered)
- Pros: Sortable, includes timestamp, better for database indexes
- Cons: Slightly predictable (timestamp component)
- Use when: You need sortable IDs or time-series data
const timeOrderedId = Uuid.v7();
Best Practices
1. Choose the Right Version
const eventId = Uuid.v7();
const token = Uuid.v4();
2. Use with RecordId
const userId = new RecordId('users', Uuid.v7());
await db.create(userId).content(userData);
try {
const uuid = Uuid.parse(userInput);
await processUuid(uuid);
} catch (error) {
return { error: 'Invalid UUID format' };
}
4. Store as UUID Type
await db.create(table).content({
session_id: Uuid.v4()
});
await db.create(table).content({
session_id: Uuid.v4().toString()
});
See Also