id-shortener
v1.0.0
Published
Efficient id / url shortener backed by pluggable storage defaulting to redis.
Downloads
2
Readme
id-shortener
Efficient id / url shortener backed by pluggable storage defaulting to redis.
Features
- Efficient, minimal short ID generation and long ID retrieval
- Pluggable storage backend defaulting to redis
- Supports node_redis and ioredis interchangeably
- Customizable short ID character set
- Defaults to base 60 to maximize URL compatibility
- Customizable idempotency
- Eg, if you shorten the same ID multiple times, you may always return the same short ID (default
idempotent: true
) or always returning unique IDs (idempotent: false
)
- Eg, if you shorten the same ID multiple times, you may always return the same short ID (default
- Thorough unit tests running against an actual instance of redis via docker-compose
Install
npm install --save id-shortener
Usage
const IdShortener = require('id-shortener')
// create a redis client as the backend
const Redis = require('ioredis')
const redisClient = new Redis('redis://localhost:6379')
const shortener = new IdShortener({
client: redisClient
})
const shortId = await shortener.shorten('test-key') => very short base60 string
const longId = await shortener.expand(shortId) // => 'test-key'
API
class IdShortener(opts)
opts.client
- object, required client to use for storage backend- currently supports instances of node_redis and ioredis
opts.characters
- string, optional character set to use for short IDs (default base 60)opts.idempotent
- boolean, optional whether or notshorten
should be idempotent (defaulttrue
)
redis-specific
opts.shortToLongKey
- string, optional key to use for short to long mapping (default'id-shortener:short-to-long'
)opts.longToShortKey
- string, optional key to use for long to short mapping (default'id-shortener:long-to-short'
)- Note this key is only used if
idempotent
istrue
- Note this key is only used if
opts.sequenceKey
- string, optional key to use for atomic id counter (default'id-shortener:sequence'
)
shorten
Returns a shortened version of the given long ID. Note this method's semantics are highly affected by the idempotent
option that was passed to the IdShortener
constructor.
IdShortener.shorten(string longId) => Promise<string shortId>
expand
Returns the long version of the given short ID. Note that this method will return undefined
if the shortId
is not found.
IdShortener.expand(string shortId) => Promise<string longId>
License
MIT © Travis Fischer
Why??? 💩
Building a URL shortener is a very, very common interview question with lots of great existing example solutions.
That being said, I couldn't find an up-to-date, open source, NodeJS module that fit my project's needs.
With this in mind, the goal of this module is not to be a perfect URL shortening solution (xkcd), as every use case will inevitably have unique differences, but rather to provide a solid example implementation for other Node devs. ✌️