Skip to content

Instantly share code, notes, and snippets.

@michaelwa
Last active July 29, 2024 05:08
Show Gist options
  • Save michaelwa/075a95215c3a23cc5ba790308e21672a to your computer and use it in GitHub Desktop.
Save michaelwa/075a95215c3a23cc5ba790308e21672a to your computer and use it in GitHub Desktop.
Elixir Organization for multitenant
defmodule MyAshPhoenixApp.Client.Organization do
use Ash.Resource,
domain: MyAshPhoenixApp.Client,
data_layer: AshPostgres.DataLayer
defimpl Ash.ToTenant do
# %{:domain => _, :id => _, _ => _}
# def to_tenant(resource, %MyAshPhoenixApp.Client.Organization{id: id}) do ## ----->>>>> this line causes a compilation error
def to_tenant(resource, %{:domain => domain, :id => id}) do ## ---->>>> this line creates a warning
if Ash.Resource.Info.data_layer(resource) == AshPostgres.DataLayer
&& Ash.Resource.Info.multitenancy_strategy(resource) == :context do
domain
else
id
end
end
end
postgres do
table "organizations"
repo MyAshPhoenixApp.Repo
manage_tenant do
template ["", :domain]
create? true
update? false
end
end
identities do
identity :unique_domain, [:domain]
end
code_interface do
define :create, action: :create
define :read_all, action: :read
define :update, action: :update
define :destroy, action: :destroy
define :get_by_id, args: [:id], action: :by_id
define :get_by_domain, args: [:domain], action: :by_domain
end
actions do
defaults [:read, :destroy]
create :create do
accept [:name, :domain]
end
update :update do
accept [:name]
end
read :by_id do
argument :id, :string, allow_nil?: false
get? true
filter expr(id == ^arg(:id))
end
read :by_domain do
argument :domain, :string, allow_nil?: false
get? true
filter expr(domain == ^arg(:domain))
end
end
attributes do
uuid_primary_key :id
attribute :name, :string do
allow_nil? false
end
attribute :domain, :string do
allow_nil? false
end
attribute :go_live_date, :naive_datetime
attribute :is_live, :boolean do
default false
end
attribute :email_domains, {:array, :string} do
default []
end
timestamps()
end
relationships do
has_many :villages, MyAshPhoenixApp.Client.Department do
source_attribute :id
destination_attribute :organization_id
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment