AshObjectIds (ash_object_ids v0.2.0)
View SourceA helper library for working with object IDs in Ash.
Object IDs are identifiers that are prefixed with the resource they identify. A more detailed explanation can be found in the "Designing APIs for humans" blog post.
This library provides an implementation for Ash:
defmodule App.Blog.Post do
use Ash.Resource,
domain: App.Blog,
data_layer: Ash.DataLayer.AshPostgres,
defmodule Id do
use AshObjectIds.Type, prefix: "p", uuid_type: :uuid_v7
end
attributes do
attribute :id, Id do
primary_key?(true)
public?(true)
writable?(false)
default(&Id.generate/0)
allow_nil?(false)
end
# ... other attributes
end
endThe IDs are base58-encoded UUIDs with a prefix.
Summary
Functions
Decodes the given object ID into a string version of the UUID.
Same as map_prefixes_to_resources, but returns only the entries that
contain more than resource for the given prefix.
Same as find_resource_for_prefix/2 but accepts a (valid) object ID.
Searches the given domains for the resource that matches the given object ID prefix.
Create a map of prefixes to the resources that use that prefix.
Functions
Decodes the given object ID into a string version of the UUID.
Examples
iex> decode_object_id("user_Cd4WBXFmobLLv7gfB4MuH")
{:ok, "5d446d08-df6a-404d-a1e5-decc78429b3d"}
iex> decode_object_id("something else")
:error
Same as map_prefixes_to_resources, but returns only the entries that
contain more than resource for the given prefix.
This function can be used to warn whenever duplicate prefixes are present in your modules. For example, in a test:
test "there are no duplicate object id prefixes" do
domains = Application.fetch_env!(:my_otp_app, :ash_domains)
assert AshObjectIds.find_duplicate_prefixes(domains) == %{}
end
Same as find_resource_for_prefix/2 but accepts a (valid) object ID.
Examples
iex> find_resource_for_id(domains, "user_CWzLBdFy2f1XhrtesFferY")
MyApp.Accounts.User
iex> find_resource_for_id(domains, "florb_CWzLBdFy2f1XhrtesFferY")
nil
Searches the given domains for the resource that matches the given object ID prefix.
You can get the domains through Application.get_env(:my_otp_app, :ash_domains, [])
Examples
iex> find_resource_for_prefix(domains, "user")
MyApp.Accounts.User
iex> find_resource_for_prefix(domains, "florb")
nil
Create a map of prefixes to the resources that use that prefix.