Files
agregarr/server/utils/idGenerator.ts

49 lines
1.5 KiB
TypeScript

import { getSettings } from '@server/lib/settings';
/**
* Generates sequential numeric IDs starting from 10000
* All collection configs share the same ID space to avoid conflicts
* Thread-safe implementation to prevent duplicate IDs
*/
export class IdGenerator {
private static readonly ID_LOCK = Symbol('idGenerationLock');
private static lockPromise: Promise<void> | null = null;
private static readonly STARTING_ID = 10000;
/**
* Generate the next sequential ID for any collection config
* Thread-safe implementation using an in-memory counter
*/
public static generateId(): string {
const settings = getSettings();
// Get current next ID or start from 10000
const currentId = settings.main.nextConfigId || this.STARTING_ID;
// Update settings with next ID immediately (synchronous)
settings.main.nextConfigId = currentId + 1;
settings.save();
return currentId.toString();
}
/**
* Get the next ID that would be generated without consuming it
* Useful for previews or planning
*/
public static getNextId(): string {
const settings = getSettings();
const nextId = settings.main.nextConfigId || this.STARTING_ID;
return nextId.toString();
}
/**
* Check if an ID was generated by our system
* Our IDs are numeric strings >= 10000
*/
public static isGeneratedId(id: string): boolean {
const numericId = parseInt(id, 10);
return !isNaN(numericId) && numericId >= this.STARTING_ID;
}
}