Nathan Long
Nathan Long

Reputation: 125882

Error while trying to use `Phoenix.Token` in a Mix task

I have a Phoenix application that uses Phoenix.Token to sign and verify tokens.

This works fine within the app itself, but I get a strange error when trying to use Phoenix.Token from a Mix task.

Here's a minimal example:

defmodule Mix.Tasks.SignSomething do
  use Mix.Task
  alias MyApp.Endpoint

  @shortdoc "sign something"

  def run(_args) do
    IO.inspect Phoenix.Token.sign(Endpoint, "key", "val")
  end
end

When I run this task, I see:

** (ArgumentError) argument error
    (stdlib) :ets.lookup(MyApp.Endpoint, :secret_key_base)
    lib/phoenix/endpoint.ex:505: Mealthy.Web.Endpoint.config/2
    (phoenix) lib/phoenix/token.ex:201: Phoenix.Token.get_endpoint_key_base/1

This appears to imply that I haven't configured :secret_key_base, but that's not true; it's in config.exs, and if I IO.puts directly after configuring it, I see that output.

How do I fix this?

Upvotes: 0

Views: 196

Answers (1)

Nathan Long
Nathan Long

Reputation: 125882

Start the App

Michał Muskała answered this question for me in the Elixir Slack. He said:

The ets table is not started, because the endpoint is not started

ets argument errors are pretty annoying :(

One solution, as he pointed out, is to start the app like this:

Mix.Task.run("app.start")

So the task becomes:

defmodule Mix.Tasks.SignSomething do
  use Mix.Task
  alias MyApp.Endpoint

  @shortdoc "sign something"

  def run(_args) do
    Mix.Task.run("app.start") # added this
    IO.inspect Phoenix.Token.sign(Endpoint, "key", "val")
  end
end

With the app started, the task can call other functions which depend on Phoenix.Token functions.

Upvotes: 4

Related Questions