@storm-stack/unique-identifier
Version:
This package provides a simple way to generate various types of unique identifiers.
99 lines (98 loc) • 2.57 kB
TypeScript
/**
* Options passed to the `generate` function to create a snowflake identifier.
*/
export interface ISnowflakeGeneratorOptions {
/**
* The id of the shard running this generator.
*
* @defaultValue 1
*/
shardId?: number;
/**
* The epoch to use for the snowflake.
*
* @remarks
* This is the time in milliseconds since 1 January 1970 00:00:00 UTC.
*
* @defaultValue 1420070400000 (Date.UTC(1970, 0, 1).valueOf())
*/
epoch?: number;
/**
* The current timestamp to use for the snowflake.
*
* @defaultValue Date.now()
*/
timestamp?: number | Date;
}
/**
* Resolvable value types for a valid Snowflake:
* * string
* * number
* * bigint
*/
export type SnowflakeResolvable = string;
/**
* A deconstructed snowflake and the details around it's creation.
*/
export interface DeconstructedSnowflake {
/**
* Snowflake deconstructed from
*/
snowflake: SnowflakeResolvable;
/**
* The timestamp the snowflake was generated
*/
timestamp: number;
/**
* The shard_id used when generating
*/
shard_id: number;
/**
* The increment of this snowflake
*/
sequence: number;
/**
* The 64Bit snowflake binary string
*/
binary: string;
}
export declare const DEFAULT_SHARD_ID = 1;
export declare const DEFAULT_EPOCH: number;
/**
* Generate a snowflake identifier.
*
* @remarks
* Snowflakes are 64-bit unsigned integers that are roughly time-ordered.
*
* @example
* ```typescript
*
* // Generate a snowflake with the default options
* const id1 = snowflake();
*
* // Generate a snowflake with a custom shard id
* const id2 = snowflake({ shardId: 2 });
*
* // Generate a snowflake with a custom shard id and timestamp
* const id3 = snowflake({ shardId: 3, timestamp: new Date("2021-01-01") });
*
* ```
*
* @param options - The options to use when generating the snowflake
* @returns A snowflake
*/
export declare function snowflake({ shardId, epoch, timestamp }: ISnowflakeGeneratorOptions): string;
/**
* Deconstruct a snowflake to its values using the `epoch`.
*
* @param snowflake - Snowflake to deconstruct
* @returns Either the DeconstructedSnowflake object
*/
export declare function deconstructSnowflake(snowflake: SnowflakeResolvable): DeconstructedSnowflake;
/**
* Check if a snowflake string Id is valid.
*
* @param snowflake - Snowflake to check
* @returns Whether the snowflake is valid
*/
export declare function isValidSnowflake(snowflake: string): boolean;