Skip to content

Repository files navigation

@shiny/id

test

Generate Stripe-style Snowflake IDs. For why you might want to do this, refer to this article: Designing APIs for humans: Object IDs.

Caution

Currently in preview stage, please use with caution

Installation

bun add @shiny/id

Generate Shiny ID

import{generateShinyId}from'@shiny/id'constid=generateShinyId({prefix: 'usr',})// Output example: usr_8lUf4MDxgEy

Underlying implementation: Uses nodejs-snowflake to generate a bigint snowflake, converts it to base62 format, and adds a user-defined prefix. Note: Theoretically generates up to 1,024,000 IDs per second, naturally blocking.

Important

This character format ID cannot be sorted correctly in the database. You can also store the original snowflake bigint value as the ID in the database and display the base62 format ID on the user side, e.g. getRawNumberFromShinyId('usr_8lUf4MDxgEy')

Custom Epoch

Using a Custom Epoch instead of the default 1970 will make your generated IDs shorter. For example, in my current test, with epoch set to default 0, the generated ID is usr_8lUf4MDxgEy; while with epoch set to current time, the generated ID is usr_yM0lunVA, which is 3 characters shorter.

import{generateShinyId}from'@shiny/id'constcustomEpoch=1754074255256constid=generateShinyId({prefix: 'usr',epoch: customEpoch})

Custom Separator

The default separator is _, because double-clicking such an ID will automatically select the text — while - does not. You can customize the separator.

import{generateShinyId}from'@shiny/id'constid=generateShinyId({prefix: 'usr',separator: '-'})

Instance ID

Due to the speed of single-machine Snowflake generation, multiple instance IDs are suitable for distributed ID generation. The instanceId range is 0 - 4095, and when not set, it defaults to a random number.

import{generateShinyId}from'@shiny/id'constid=generateShinyId({prefix: 'usr',instanceId: 1,})constinstanceId=getInstanceIdFromShinyId(id)

License

MIT

About

Generate Stripe-style Snowflake IDs.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages