Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/custom scope opts #5

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 24 additions & 5 deletions lib/pow/ecto/context.ex
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ defmodule Pow.Ecto.Context do
@spec get_by(Keyword.t() | map(), Config.t()) :: user() | nil
def get_by(clauses, config) do
user_mod = Config.user!(config)
clauses = normalize_user_id_field_value(user_mod, clauses)
clauses = Keyword.merge(normalize_user_id_field_value(user_mod, clauses), scope_opts(config))
opts = repo_opts(config, [:prefix])

Config.repo!(config).get_by(user_mod, clauses, opts)
Expand All @@ -192,9 +192,12 @@ defmodule Pow.Ecto.Context do
@spec do_insert(changeset(), Config.t()) :: {:ok, user()} | {:error, changeset()}
def do_insert(changeset, config) do
opts = repo_opts(config, [:prefix])
repo = Config.repo!(config)
scope = scope_opts(config)

repo.insert(changeset, opts)
changeset
|> Ecto.Changeset.change(scope)
|> Config.repo!(config).insert(opts)
|> reload_after_write(config)
end

@doc """
Expand All @@ -205,9 +208,23 @@ defmodule Pow.Ecto.Context do
@spec do_update(changeset(), Config.t()) :: {:ok, user()} | {:error, changeset()}
def do_update(changeset, config) do
opts = repo_opts(config, [:prefix])
repo = Config.repo!(config)
scope = scope_opts(config)

repo.update(changeset, opts)
changeset
|> Ecto.Changeset.change(scope)
|> Config.repo!(config).update(opts)
|> reload_after_write(config)
end

defp reload_after_write({:error, _} = err, _), do: err

defp reload_after_write({:ok, struct}, config) do
# When ecto updates/inserts, has_many :through associations are set to nil, so need to reload
# when writes happen.
opts = repo_opts(config, [:prefix])
struct = Config.repo!(config).get!(struct.__struct__, struct.id, opts)

{:ok, struct}
end

# TODO: Remove by 1.1.0
Expand All @@ -220,6 +237,8 @@ defmodule Pow.Ecto.Context do
|> Keyword.take(opts)
end

defp scope_opts(config), do: Config.get(config, :scope_opts, [])

# TODO: Remove by 1.1.0
@deprecated "Use `Pow.Config.user!/1` instead"
defdelegate user_schema_mod(config), to: Config, as: :user!
Expand Down
Loading