Skip to content

Instantly share code, notes, and snippets.

@jsullivanlive
Last active December 17, 2020 20:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsullivanlive/250e0de33b39d588aedad60781307c43 to your computer and use it in GitHub Desktop.
Save jsullivanlive/250e0de33b39d588aedad60781307c43 to your computer and use it in GitHub Desktop.
SalesforceID.js
/**
* helper class to manage incrementing salesforce ids
* Author: CloudAnswers
* License: AGPL3
*/
const caseSafeId = require("./caseSafeId");
const base62 = require("base-x")(
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
);
const base10 = require("base-x")("0123456789");
class SalesforceID {
prefix = "";
suffix = "";
number = 0;
constructor(id) {
if (!id) return;
if (typeof id !== "string") {
throw new Error("not string:" + id);
}
if (id.length < 15) {
throw new Error("string too short:" + JSON.stringify(id));
}
id = caseSafeId(id).substr(0, 15); // chop off last 3 since it's checksum, not part of the number
this.prefix = id.substring(0, 5);
this.suffix = id.substring(5);
var idAsBuffer = base62.decode(this.suffix);
this.number = new Number(base10.encode(idAsBuffer));
}
next(increment = 1) {
var nextSalesforceId = new SalesforceID();
nextSalesforceId.prefix = this.prefix;
nextSalesforceId.number = this.number + increment;
return nextSalesforceId;
}
toString() {
let encodedString = base62.encode(base10.decode(this.number.toString()));
// remove leading zeros
encodedString = encodedString.replace(/^0+/, "");
// set to right length
encodedString = encodedString.padStart(10, "0");
encodedString = this.prefix + encodedString;
return caseSafeId(encodedString);
}
}
module.exports = SalesforceID;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment