Typeid (elixir_typeid v0.2.0)

View Source

An Elixir implementation of TypeID, and a formal specification defines the encoding in more detail.

Summary

Types

t()

A struct to describe a Typeid.

Functions

Generate a new t/0 with the given type (as its prefix).

Parse a t/0 from a string, if there is not given the prefix part of the Typeid, the prefix of the parsed t/0 is processed as nil.

Transfer a t/0 into a string.

Extract the UUIDv7 from the t/0, the return UUIDv7 struct depends Uniq.UUID.

Validate a t/0 or a string TypeID format.

Types

t()

@type t() :: %Typeid{prefix: String.t(), suffix: String.t()}

A struct to describe a Typeid.

Functions

new(type)

@spec new(String.t()) :: {:ok, t()} | :error

Generate a new t/0 with the given type (as its prefix).

Refer TypeID's specification, the given type can be a nil or an empty string "".

Example

iex> Typeid.new("user")
{:ok, #Typeid<"user_01hzep1kb6ea1abhrg1zx021h8">}
iex> Typeid.new(nil)
{:ok, #Typeid<"01hzevjrxwf4b831t5vshyt571">}
iex> Typeid.new("")
{:ok, #Typeid<"01hzevjvc5fp0avt85w4z35wnw">}

parse(string)

@spec parse(String.t()) :: {:ok, t()} | :error

Parse a t/0 from a string, if there is not given the prefix part of the Typeid, the prefix of the parsed t/0 is processed as nil.

Example

iex> Typeid.parse("user_01hzep7s63fd5ted6f7wgqmx3m")
{:ok, #Typeid<"user_01hzep7s63fd5ted6f7wgqmx3m">}
iex> {:ok, typeid} = Typeid.parse("01hzep7s63fd5ted6f7wgqmx3m")
{:ok, #Typeid<"01hzep7s63fd5ted6f7wgqmx3m">}
iex> typeid.prefix
nil

to_string(typeid)

@spec to_string(typeid :: t()) :: String.t()

Transfer a t/0 into a string.

Example

iex> {:ok, typeid} = Typeid.new("user")
{:ok, #Typeid<"user_01hzep7s63fd5ted6f7wgqmx3m">}
iex> Typeid.to_string(typeid)
"user_01hzep7s63fd5ted6f7wgqmx3m"

uuid(typeid)

@spec uuid(typeid :: t()) :: {:ok, Uniq.UUID.info()} | :error

Extract the UUIDv7 from the t/0, the return UUIDv7 struct depends Uniq.UUID.

Example

iex> {:ok, typeid} = Typeid.new("user")
{:ok, #Typeid<"user_01hzep7s63fd5ted6f7wgqmx3m">}
iex> Typeid.uuid(typeid)
{:ok, #UUIDv7<018fdd63-e4c3-7b4b-a734-cf3f217a7474>}

valid?(typeid)

@spec valid?(typeid :: t()) :: boolean()
@spec valid?(typeid :: String.t()) :: boolean()

Validate a t/0 or a string TypeID format.

Example

iex> {:ok, typeid} = Typeid.new("user")
{:ok, #Typeid<"user_01hzep7s63fd5ted6f7wgqmx3m">}
iex> Typeid.valid?(typeid)
true
iex> Typeid.valid?("user_01hzep7s63fd5ted6f7wgqmx3m")
true
iex> Typeid.valid?("user_01hzep7s63fd5ted6f7wgqmx3")
false