uuid
UUID generation skill - Universally Unique Identifiers v4 and v7 for entity IDs. For ng-events construction site progress tracking system.
What this skill does
# UUID - Universally Unique Identifiers Trigger patterns: "UUID", "unique ID", "identifier", "v4", "v7", "uuidv4", "uuidv7" ## Overview UUID library for generating RFC9562-compliant unique identifiers in JavaScript/TypeScript applications. **Package**: [email protected] **Standard**: RFC9562 (formerly RFC4122) ## Core Functions ### 1. v4() - Random UUID (Most Common) Generates a version 4 UUID using cryptographically secure random values. ```typescript import { v4 as uuidv4 } from 'uuid'; // Generate random UUID const taskId = uuidv4(); // '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' // Use in entity creation interface Task { id: string; title: string; createdAt: Date; } function createTask(title: string): Task { return { id: uuidv4(), title, createdAt: new Date() }; } ``` **When to use**: - Entity IDs (tasks, users, blueprints) - Session IDs - Request tracking IDs - File upload IDs - Any unique identifier needs ### 2. v7() - Timestamp-based UUID (Sortable) Generates a version 7 UUID with Unix epoch timestamp for natural chronological sorting. ```typescript import { v7 as uuidv7 } from 'uuid'; // Generate timestamp-based UUID const orderId = uuidv7(); // '019a26ab-9a66-71a9-a89e-63c35fce4a5a' // Multiple UUIDs are naturally sortable const ids = Array.from({ length: 5 }, () => uuidv7()); // All IDs will be in chronological order // Use for database primary keys interface Order { id: string; // v7 UUID - sortable by creation time customerId: string; createdAt: Date; } ``` **When to use**: - Database primary keys requiring chronological sorting - Event IDs in time-series data - Log entry IDs - Audit trail records - Any scenario where temporal ordering matters **Advantages**: - Natural sort order by creation time - Better database index performance - Reduced fragmentation in B-tree indexes - Compatible with UUID v4 in storage/APIs ## Real-World Examples ### Task Repository with UUID ```typescript import { Injectable, inject } from '@angular/core'; import { Firestore, collection, doc, setDoc, getDoc } from '@angular/fire/firestore'; import { v4 as uuidv4 } from 'uuid'; export interface Task { id: string; blueprintId: string; title: string; description: string; status: 'pending' | 'in-progress' | 'completed'; createdAt: Date; updatedAt: Date; } @Injectable({ providedIn: 'root' }) export class TaskRepository { private firestore = inject(Firestore); private tasksCollection = collection(this.firestore, 'tasks'); /** * Create task with UUID v4 */ async create(task: Omit<Task, 'id' | 'createdAt' | 'updatedAt'>): Promise<Task> { const id = uuidv4(); // Generate unique ID const now = new Date(); const newTask: Task = { ...task, id, createdAt: now, updatedAt: now }; const docRef = doc(this.tasksCollection, id); await setDoc(docRef, newTask); return newTask; } /** * Get task by UUID */ async findById(id: string): Promise<Task | null> { const docRef = doc(this.tasksCollection, id); const snapshot = await getDoc(docRef); if (!snapshot.exists()) { return null; } return { id: snapshot.id, ...snapshot.data() } as Task; } } ``` ### Audit Log with UUID v7 ```typescript import { Injectable, inject } from '@angular/core'; import { Firestore, collection, doc, setDoc } from '@angular/fire/firestore'; import { v7 as uuidv7 } from 'uuid'; export interface AuditLog { id: string; // v7 UUID for chronological sorting userId: string; action: string; resource: string; resourceId: string; timestamp: Date; metadata?: Record<string, any>; } @Injectable({ providedIn: 'root' }) export class AuditLogRepository { private firestore = inject(Firestore); private logsCollection = collection(this.firestore, 'auditLogs'); /** * Create audit log with v7 UUID (sortable by time) */ async log( userId: string, action: string, resource: string, resourceId: string, metadata?: Record<string, any> ): Promise<AuditLog> { const id = uuidv7(); // Timestamp-based UUID const log: AuditLog = { id, userId, action, resource, resourceId, timestamp: new Date(), metadata }; const docRef = doc(this.logsCollection, id); await setDoc(docRef, log); return log; } } ``` ### Session Management ```typescript import { Injectable } from '@angular/core'; import { v4 as uuidv4 } from 'uuid'; export interface Session { id: string; userId: string; token: string; createdAt: Date; expiresAt: Date; } @Injectable({ providedIn: 'root' }) export class SessionService { private sessions = new Map<string, Session>(); /** * Create new session with UUID */ createSession(userId: string, expiresInMs: number = 3600000): Session { const sessionId = uuidv4(); const now = new Date(); const session: Session = { id: sessionId, userId, token: this.generateToken(), createdAt: now, expiresAt: new Date(now.getTime() + expiresInMs) }; this.sessions.set(sessionId, session); return session; } /** * Get session by ID */ getSession(sessionId: string): Session | null { return this.sessions.get(sessionId) || null; } private generateToken(): string { return uuidv4(); // Use UUID as token } } ``` ### File Upload Tracking ```typescript import { Injectable, signal } from '@angular/core'; import { v4 as uuidv4 } from 'uuid'; export interface FileUpload { id: string; fileName: string; fileSize: number; uploadedBy: string; uploadedAt: Date; status: 'pending' | 'uploading' | 'completed' | 'failed'; progress: number; url?: string; } @Injectable({ providedIn: 'root' }) export class FileUploadService { private uploads = signal<Map<string, FileUpload>>(new Map()); /** * Start file upload with UUID tracking */ startUpload(file: File, userId: string): string { const uploadId = uuidv4(); const upload: FileUpload = { id: uploadId, fileName: file.name, fileSize: file.size, uploadedBy: userId, uploadedAt: new Date(), status: 'pending', progress: 0 }; this.uploads.update(map => { map.set(uploadId, upload); return new Map(map); }); return uploadId; } /** * Update upload progress */ updateProgress(uploadId: string, progress: number): void { this.uploads.update(map => { const upload = map.get(uploadId); if (upload) { upload.progress = progress; upload.status = progress === 100 ? 'completed' : 'uploading'; map.set(uploadId, upload); } return new Map(map); }); } /** * Get upload by ID */ getUpload(uploadId: string): FileUpload | undefined { return this.uploads().get(uploadId); } } ``` ## Best Practices ### 1. v4 for General Use, v7 for Time-Series ✅ **DO**: Choose based on use case ```typescript // General entity IDs - use v4 const taskId = uuidv4(); const userId = uuidv4(); // Time-series or sortable IDs - use v7 const logId = uuidv7(); const eventId = uuidv7(); ``` ### 2. Use TypeScript Types ✅ **DO**: Define UUID brand types for safety ```typescript type UUID = string & { readonly __brand: unique symbol }; interface Task { id: UUID; title: string; } function createTaskId(): UUID { return uuidv4() as UUID; } ``` ### 3. Validate UUIDs ✅ **DO**: Validate UUID format ```typescript import { validate as uuidValidate, version as uuidVersion } from 'uuid'; function isValidUUID(id: string): boolean { return uuidValidate(id); } function isV4UUID(id: string): boolean { return uuidValidate(id) && uuidVersion(id) === 4; } function isV7UUID(id: string): boolean { return uuidValidate(id) && uuidVersion(id) === 7; } ``` ### 4. Don't Store UUIDs as Binary (Firestore) ✅ **DO**: Store as string in Fire
Related in Data & Analytics
clawarr-suite
IncludedComprehensive management for self-hosted media stacks (Sonarr, Radarr, Lidarr, Readarr, Prowlarr, Bazarr, Overseerr, Plex, Tautulli, SABnzbd, Recyclarr, Unpackerr, Notifiarr, Maintainerr, Kometa, FlareSolverr). Deep library exploration, analytics, dashboard generation, content management, request handling, subtitle management, indexer control, download monitoring, quality profile sync, library cleanup automation, notification routing, collection/overlay management, and media tracker integration (Trakt, Letterboxd, Simkl).
querying-soql
IncludedSOQL query generation, optimization, and analysis with 100-point scoring. Use this skill when the user needs SOQL/SOSL authoring or optimization: natural-language-to-query generation, relationship queries, aggregates, query-plan analysis, and performance or safety improvements for Salesforce queries. TRIGGER when: user writes, optimizes, or debugs SOQL/SOSL queries, touches .soql files, or asks about relationship queries, aggregates, or query performance. DO NOT TRIGGER when: bulk data operations (use handling-sf-data), Apex DML logic (use generating-apex), or report/dashboard queries.
app-store-optimization
IncludedApp Store Optimization (ASO) toolkit for researching keywords, analyzing competitor rankings, generating metadata suggestions, and improving app visibility on Apple App Store and Google Play Store. Use when the user asks about ASO, app store rankings, app metadata, app titles and descriptions, app store listings, app visibility, or mobile app marketing on iOS or Android. Supports keyword research and scoring, competitor keyword analysis, metadata optimization, A/B test planning, launch checklists, and tracking ranking changes.
habit-flow
IncludedAI-powered atomic habit tracker with natural language logging, streak tracking, smart reminders, and coaching. Use for creating habits, logging completions naturally ("I meditated today"), viewing progress, and getting personalized coaching.
app-store-optimization
IncludedApp Store Optimization (ASO) toolkit for researching keywords, analyzing competitor rankings, generating metadata suggestions, and improving app visibility on Apple App Store and Google Play Store. Use when the user asks about ASO, app store rankings, app metadata, app titles and descriptions, app store listings, app visibility, or mobile app marketing on iOS or Android. Supports keyword research and scoring, competitor keyword analysis, metadata optimization, A/B test planning, launch checklists, and tracking ranking changes.
visualizing-data
IncludedBuilds dashboards, reports, and data-driven interfaces requiring charts, graphs, or visual analytics. Provides systematic framework for selecting appropriate visualizations based on data characteristics and analytical purpose. Includes 24+ visualization types organized by purpose (trends, comparisons, distributions, relationships, flows, hierarchies, geospatial), accessibility patterns (WCAG 2.1 AA compliance), colorblind-safe palettes, and performance optimization strategies. Use when creating visualizations, choosing chart types, displaying data graphically, or designing data interfaces.