Created
November 22, 2021 04:38
-
-
Save romansorin/c25e8cbe132ae34bf19ee91e5926a364 to your computer and use it in GitHub Desktop.
A utility to hide primary keys and database ids using the Hashids package
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Hashids = require("hashids/cjs"); | |
export class Hash { | |
private hashids; | |
/** | |
* Creates a Hash object. | |
* | |
* @param {string} salt The unique salt/alphabet to use for salting. Setting a salt allows output hashes to be more unique. | |
* @param {number} padding The minimum output length of the hash (default is 6). | |
*/ | |
constructor(salt: string = "", padding: number = 6) { | |
this.hashids = new Hashids(salt, padding); | |
} | |
/** | |
* Encodes the provided ID argument and returns a string representing the hash. | |
* | |
* @param {number} id The numeric "id" to be encoded or turned into a hash. | |
* @returns {string} Returns the encoded ID in the form of a hash, e.g. "o2fXhV" | |
*/ | |
public encodeId(id: number) { | |
return this.hashids.encode(id); | |
} | |
/** | |
* Decodes the provided hash argument and returns a number representing the ID. | |
* | |
* @param {string} id The numeric "id" to be encoded or turned into a hash. | |
* @returns {number} Returns the numeric ID, e.g. "1" | |
*/ | |
public decodeId(hash: string) { | |
const decoded = this.hashids.decode(hash); | |
return decoded.length > 1 ? decoded : decoded[0]; | |
} | |
/** | |
* Sets the internal hashids object with the provided salt/padding arguments. | |
* | |
* @param {string} salt The unique salt/alphabet to use for salting. Setting a salt allows output hashes to be more unique. | |
* @param {number} padding The minimum output length of the hash (default is 6). | |
*/ | |
public setHashids(salt: string = "", padding: number = 6) { | |
this.hashids = new Hashids(salt, padding); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment