Neurotoxin Powered Marketing
Wondering what’s next for npm?Check out our public roadmap! »

id-shortener

1.0.0 • Public • Published

id-shortener

Efficient id / url shortener backed by pluggable storage defaulting to redis.

NPM Build Status JavaScript Style Guide

Features

  • Efficient, minimal short ID generation and long ID retrieval
  • Pluggable storage backend defaulting to redis
  • 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)
  • 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
  • opts.characters - string, optional character set to use for short IDs (default base 60)
  • opts.idempotent - boolean, optional whether or not shorten should be idempotent (default true)

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 is true
  • 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. ✌️

Keywords

none

Install

npm i id-shortener

DownloadsWeekly Downloads

2

Version

1.0.0

License

MIT

Last publish

Collaborators

  • avatar