View Source Carve.HashIds (Carve v0.3.0)
Carve.HashIds provides functionality for encoding and decoding IDs using HashIds.
This module is responsible for:
- Configuring the HashIds settings
- Encoding integer IDs into hashed strings
- Decoding hashed strings back into integer IDs
- Handling entity-specific salting for added security
It uses the Hashids library internally and provides a convenient API for Carve users.
Summary
Functions
Configures the HashIds settings.
Decodes a hashed string without specifying the entity type.
Decodes a hashed string back into an integer ID for a given type.
Encodes an integer ID for a given type into a hashed string.
Functions
Configures the HashIds settings.
This function sets up the salt and minimum length for HashIds encoding. It stores these settings in persistent term storage for efficient access.
Parameters
opts
: A keyword list of configuration options.:salt
- The salt used for hashing (default: 1207:Rumi):min_length
- The minimum length of generated hashes (default: 4)
Example
iex> Carve.HashIds.configure(salt: "my_custom_salt", min_length: 8)
:ok
Decodes a hashed string without specifying the entity type.
This function attempts to decode the hash without verifying the entity type.
Parameters
hash
: The hashed string to be decoded
Returns
{:ok, id}
if decoding is successful, where id
is the original integer ID.
{:error, reason}
for decoding errors.
Example
iex> Carve.HashIds.decode("Xk9Lp2Rr4m")
{:ok, 123}
Decodes a hashed string back into an integer ID for a given type.
Parameters
type
: An atom representing the entity type (e.g., :user, :post)hash
: The hashed string to be decoded
Returns
{:ok, id}
if decoding is successful, where id
is the original integer ID.
{:error, :invalid_entity_type}
if the decoded salt doesn't match the given type.
{:error, reason}
for other decoding errors.
Example
iex> Carve.HashIds.decode(:user, "Xk9Lp2Rr4m")
{:ok, 123}
Encodes an integer ID for a given type into a hashed string.
Parameters
type
: An atom representing the entity type (e.g., :user, :post)id
: The integer ID to be encoded
Returns
A string representing the encoded ID.
Example
iex> Carve.HashIds.encode(:user, 123)
"Xk9Lp2Rr4m"