https://github.com/chronark/prefixed-id
Generate prefixed ids just like stripe: sk_helloworld
https://github.com/chronark/prefixed-id
Last synced: 10 months ago
JSON representation
Generate prefixed ids just like stripe: sk_helloworld
- Host: GitHub
- URL: https://github.com/chronark/prefixed-id
- Owner: chronark
- License: mit
- Created: 2022-12-10T15:42:48.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2022-12-10T15:59:53.000Z (over 3 years ago)
- Last Synced: 2025-01-11T23:03:07.079Z (over 1 year ago)
- Language: TypeScript
- Size: 36.1 KB
- Stars: 6
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
@chronark/prefixed-id
pre_JUbF9zRGz9hrFXUyNJLXcowD9GsqCD
A minimal library to generate Stripe inspired predixed ids for your application.
Prefixed ids look like this: `pre_JUbF9zRGz9hrFXUyNJLXcowD9GsqCD`. They can be very useful if you
have different entities and want to quickly identify them.
Generated ids rely on the provided crypto implementation. If you use either `window.crypto` or
`crypto` from "node:crypto", the ids will be cryptographically secure.
Works in
- Nodejs
- Cloudflare Workers
- Vercel Edge
## Install
```
npm i @chronark/prefixed-id
```
## Usage
### Nodejs
```ts
import nodeCrypto from "node:crypto"
const idGenerator = new IdGenerator({
prefixes: {
"user": "u",
},
crypto: nodeCrypto
})
console.log(idGenerator.id("user"))
// u_PtbBA7NGcYYDpae6ULWujk
```
### WebCrypto
- Cloudflare Workers
- Vercel Edge
```ts
const idGenerator = new IdGenerator({
prefixes: {
"user": "u",
},
crypto: crypto // will be globally defined
})
console.log(idGenerator.id("user"))
// u_PtbBA7NGcYYDpae6ULWujk
```
## Options
You may pass these options to the constructor to customize the id generation.
```ts
{
/**
*
* @default "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
*/
alphabet?: string;
/**
* Either window.crypto or crypto from node
*
* @default window?.crypto
*/
crypto?: Crypto;
/**
* Byte size of the generated id
*/
size?: number;
};
```