A simple Snowflake Id package for NestJS
Installations
npm install @street-devs/nest-snowflake-id
Developer Guide
Typescript
No
Module System
CommonJS
Node Version
16.20.2
NPM Version
8.19.4
Score
66.1
Supply Chain
97.5
Quality
86.9
Maintenance
100
Vulnerability
100
License
Releases
Contributors
Unable to fetch Contributors
Languages
JavaScript (64.61%)
TypeScript (35.39%)
Developer
street-devs
Download Statistics
Total Downloads
1,450
Last Day
5
Last Week
28
Last Month
229
Last Year
1,450
GitHub Statistics
11 Stars
12 Commits
1 Forks
1 Watching
1 Branches
1 Contributors
Bundle Size
4.78 kB
Minified
1.52 kB
Minified + Gzipped
Package Meta Information
Latest Version
2.0.8
Package Id
@street-devs/nest-snowflake-id@2.0.8
Unpacked Size
14.36 kB
Size
5.12 kB
File Count
12
NPM Version
8.19.4
Node Version
16.20.2
Publised On
26 Dec 2024
Total Downloads
Cumulative downloads
Total Downloads
1,450
Last day
0%
5
Compared to previous day
Last week
33.3%
28
Compared to previous week
Last month
-51.6%
229
Compared to previous month
Last year
0%
1,450
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
1
Peer Dependencies
3
Dev Dependencies
22
@street-devs/nest-snowflake-id
- User Guide
Overview
The @street-devs/nest-snowflake-id
package provides a highly customizable Snowflake ID generator for NestJS applications. This generator produces unique 64-bit IDs based on the Snowflake algorithm, which consists of a timestamp, a node (instance) ID, and a sequence number. It also includes decoding capabilities to extract the components of generated IDs.
Key Features:
- Customizable epoch: You can specify a custom start epoch for the ID generation.
- Worker and Data Center IDs: Each instance of the generator can have its own node ID, ensuring that generated IDs are unique across across multiple machines and data centers.
- Concurrency-safe: Handles sequence numbers within the same millisecond to avoid collisions.
Installation
To install the package in your NestJS project, run:
1npm install --save @street-devs/nest-snowflake-id
Usage
1. Importing and Configuring the Module
To use @street-devs/nest-snowflake-id
in your NestJS application, you need to import the module and configure it.
Example: Basic Usage
1import { Module } from '@nestjs/common'; 2import { SnowflakeIdModule } from '@street-devs/nest-snowflake-id'; 3 4@Module({ 5 imports: [SnowflakeIdModule.forRoot()], 6}) 7export class AppModule {}
Example: Custom Configuration
You can provide custom options:
1import { Module } from '@nestjs/common'; 2import { SnowflakeIdModule } from '@street-devs/nest-snowflake-id'; 3 4import { Module } from '@nestjs/common'; 5import { SnowflakeIdModule } from 'nest-snowflake-id'; 6 7@Module({ 8 imports: [SnowflakeIdModule.forRoot({ 9 customEpoch: 1609459200000, // Custom epoch (Jan 1, 2021) 10 dataCenterId: 1, // Data Center ID 11 workerId: 1, // Worker ID 12 })], 13}) 14export class AppModule {}
customEpoch
is an optional UNIX timestamp that marks the start of your Snowflake IDs. If not provided, the current time is used.dataCenterId
allows you to set a unique data center ID, which should be between 0 and 31 (based on 5-bit configuration).workerId
: allows you to set a unique worker ID, which should be between 0 and 31 (based on 5-bit configuration).
2. Generating IDs
You can generate Snowflake IDs by injecting the SnowflakeIdService
into your service or controller.
Example: ID Generation
1import { Injectable } from '@nestjs/common'; 2import { SnowflakeIdService } from '@street-devs/nest-snowflake-id'; 3 4@Injectable() 5export class MyService { 6 constructor(private readonly snowflakeIdService: SnowflakeIdService) {} 7 8 generateId() { 9 const id = this.snowflakeIdService.generate(); 10 console.log(`Generated Snowflake ID: ${id}`); 11 return id; 12 } 13}
The generate()
method will return a unique 64-bit Snowflake ID as a bigint
.
3. Decoding IDs
You can also decode a Snowflake ID to extract its timestamp, instance ID, and sequence number.
Example: ID Decoding
1import { Injectable } from '@nestjs/common'; 2import { SnowflakeIdService } from '@street-devs/nest-snowflake-id'; 3 4@Injectable() 5export class MyService { 6 constructor(private readonly snowflakeIdService: SnowflakeIdService) {} 7 8 decodeId(id: bigint) { 9 const decoded = this.snowflakeIdService.decode(id); 10 console.log(`Decoded Snowflake ID:`, decoded); 11 return decoded; 12 } 13}
The decode()
method will return an object containing:
dateTime
: The exact date and time when the ID was generated.timestamp
: Raw timestamp value.dataCenterId
: The ID of the data center.workerId
: The ID of the worker node.sequence
: The sequence number ensuring uniqueness within the same millisecond.epoch
: The custom epoch used.
4. Global Module Usage
If you want to make the SnowflakeIdService
globally available throughout your application, set the global
option to true
:
1@Module({ 2 imports: [SnowflakeIdModule.forRoot({ global: true })], 3}) 4export class AppModule {}
API Reference
SnowflakeIdService Methods
-
generate()
: Generates a unique 64-bit Snowflake ID.- Returns:
bigint
- Returns:
-
decode(id: bigint)
: Decodes the given Snowflake ID.- Parameters:
id
: The Snowflake ID to decode.
- Returns:
{ dateTime: Date, timestamp: bigint, dataCenterId: bigint, workerId: bigint, sequence: bigint, epoch: number }
- Parameters:
Technical Details
ID Structure (64 bits):
- Epoch (42 bits): Used to store the timestamp (up to 139 years).
- Worker ID (5 bits): Identifies the node generating the ID (supports up to 32 workers).
- Data Center ID (5 bits): Identifies the data center (supports up to 32 data centers).
- Sequence (12 bits): Ensures uniqueness within the same millisecond (can generate up to 4096 IDs per millisecond).
Edge Cases:
- When multiple IDs are generated within the same millisecond, the sequence number will increment. If the sequence number reaches the limit (1023), the generator waits for the next millisecond.
Example Use Case
1const snowflake = new SnowflakeId({ 2 customEpoch: 1609459200000, 3 dataCenterId: 1, 4 workerId: 1 5}); 6const newId = snowflake.generate(); 7console.log(newId); // Example output: 93977444276639021 8const decoded = snowflake.decode(newId); 9console.log(decoded); 10// { 11// "dateTime": "2024-09-16T07:52:48.732Z", 12// "timestamp": 1726473168732, 13// "dataCenterId": 1, 14// "workerId": 1, 15// "sequence": 1325, 16// "epoch": 1704067200000 17// }
License
This package is open-sourced under the MIT License.
No vulnerabilities found.
No security vulnerabilities found.