@mixmaxhq/url-id

0.1.3 • Public • Published

url-id

A utility for encoding and parsing tiny, url-safe objects of identifiers

Install

$ npm install @mixmaxhq/url-id

Usage

Create an Encoder instance, define encoding/decoding rules on it, and begin encoding objects.

const Encoder = require('url-id');

// The default context to encode/decode in.
const encoder = new Encoder('main');

encoder.define('main', {
  token: 'g',
  match: (obj) => obj && obj.type === 'gmailMessageId',
  encode(obj) {
    this.assert(typeof obj.userId === 'string');
    return this.encode('id', obj.userId) + this.encode('id', obj.gmailMessageId);
  },
  decode() {
    const data = {
      type: 'gmailMessageId'
    };

    [data.userId, data.gmailMessageId] = this.decode('id', 2);
    return data;
  }
});

encoder.define('id', {
  token: 'z',
  encode(input) {
    return this.string(input, 'utf8');
  },
  decode() {
    return this.string('utf8');
  }
});

const exampleData = {
  type: 'gmailMessageId',
  userId: '76456789976',
  gmailMessageId: 'some id here (full unicode)'
};

encoder.encode(exampleData);
// => gzALNzY0NTY3ODk5NzYzAbc29tZSBpZCBoZXJlIChmdWxsIHVuaWNvZGUp
//    (length: 58)

encoder.decode('gzALNzY0NTY3ODk5NzYzAbc29tZSBpZCBoZXJlIChmdWxsIHVuaWNvZGUp');
// => { type: 'gmailMessageId',
//      userId: '76456789976',
//      gmailMessageId: 'some id here (full unicode)' }

// compare to just base64-encoding JSON.stringify:
Buffer.from(JSON.stringify(exampleData)).toString('base64');
// eyJ0eXBlIjoiZ21haWxNZXNzYWdlSWQiLCJ1c2VySWQiOiI3NjQ1Njc4OTk3NiIsImdtYWlsTWVzc2FnZUlkIjoic29tZSBpZCBoZXJlIChmdWxsIHVuaWNvZGUpIn0=
// (length: 128)

License

The MIT License

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 0.1.3
    29
    • latest

Version History

  • Version
    Downloads (Last 7 Days)
    • Published
  • 0.1.3
    29
  • 0.1.2
    0
  • 0.1.1
    0
  • 0.1.0
    0

Package Sidebar

Install

npm i @mixmaxhq/url-id

Weekly Downloads

15

Version

0.1.3

License

MIT

Unpacked Size

12.2 kB

Total Files

5

Last publish

Collaborators

  • alan-hadyk
  • leonardo-mixmax
  • dmytro.prysiazhnyi
  • laszlovaspal
  • akashbhalla
  • hishank
  • danyloderkach
  • sergey.polyarush
  • jordins
  • eugene.safronov.dewais
  • joneslloyd
  • kamilgruszka
  • tharindu-wj
  • aminao
  • enuma
  • adriandmitroca
  • mixmaxkristina
  • corridonimatias
  • mikusd
  • mixmax_it
  • andra.lazariuc
  • danaya
  • adborroto
  • aaavakian
  • dnechay
  • raphaelbs
  • guilhermemj
  • eduard.borges
  • mixmax-codeship
  • bradvogel
  • jessem3
  • jsalvata
  • gabriel-mixmax