GreenFairy.Relay.GlobalId (GreenFairy v0.3.0)
View SourceGlobal ID encoding and decoding for Relay Object Identification.
Note: This module delegates to GreenFairy.GlobalId.Base64 for backwards
compatibility. For new code, use GreenFairy.GlobalId directly, which supports
custom encoding implementations via the GreenFairy.GlobalId behaviour.
Format
Global IDs are Base64-encoded strings in the format: "TypeName:localId"
Usage
# Encoding
GlobalId.encode("User", 123)
#=> "VXNlcjoxMjM="
GlobalId.encode(:user, "abc-def")
#=> "VXNlcjphYmMtZGVm"
# Decoding
GlobalId.decode("VXNlcjoxMjM=")
#=> {:ok, {"User", "123"}}
GlobalId.decode!("VXNlcjoxMjM=")
#=> {"User", "123"}Custom Global IDs
To use a custom encoding scheme, implement the GreenFairy.GlobalId behaviour
and configure it in your schema:
use GreenFairy.Schema,
global_id: MyApp.CustomGlobalIdIn Types
Use the global_id field helper to automatically encode IDs:
type "User", struct: MyApp.User do
implements GreenFairy.BuiltIns.Node
global_id :id # Uses the type name and struct's :id field
field :email, :string
end
Summary
Functions
Decodes a global ID into its type name and local ID.
Decodes a global ID, raising on error.
Converts a global ID's local ID to an integer if possible.
Encodes a type name and local ID into a global ID.
Extracts just the local ID from a global ID.
Extracts just the type name from a global ID.
Functions
Decodes a global ID into its type name and local ID.
Returns {:ok, {type_name, local_id}} on success, or {:error, reason} on failure.
Examples
iex> GlobalId.decode("VXNlcjoxMjM=")
{:ok, {"User", "123"}}
iex> GlobalId.decode("invalid")
{:error, :invalid_global_id}
Decodes a global ID, raising on error.
Examples
iex> GlobalId.decode!("VXNlcjoxMjM=")
{"User", "123"}
Converts a global ID's local ID to an integer if possible.
Examples
iex> GlobalId.decode_id("VXNlcjoxMjM=")
{:ok, {"User", 123}}
iex> GlobalId.decode_id("VXNlcjphYmM=")
{:ok, {"User", "abc"}}
Encodes a type name and local ID into a global ID.
The type name can be an atom or string. Atoms are converted to
PascalCase (e.g., :user_profile becomes "UserProfile").
Examples
iex> GlobalId.encode("User", 123)
"VXNlcjoxMjM="
iex> GlobalId.encode(:user, "abc")
"VXNlcjphYmM="
iex> GlobalId.encode(:user_profile, 42)
"VXNlclByb2ZpbGU6NDI="
Extracts just the local ID from a global ID.
Examples
iex> GlobalId.local_id("VXNlcjoxMjM=")
{:ok, "123"}
Extracts just the type name from a global ID.
Examples
iex> GlobalId.type("VXNlcjoxMjM=")
{:ok, "User"}