HawkEx.CSV.Formatter behaviour (hawk_ex v0.1.0)

Copy Markdown View Source

Behaviour for CSV export formatters.

Implement this behaviour to export application resources through HawkEx's CSV pipeline. A formatter owns three things: the column headers, the query used to fetch scoped rows, and the conversion of each row into CSV values.

Example

defmodule MyApp.CSV.Formatters.Users do
  @behaviour HawkEx.CSV.Formatter

  import Ecto.Query
  alias MyApp.Accounts.User

  @impl true
  def headers, do: ["id", "email", "name", "inserted_at"]

  @impl true
  def to_row(%User{} = user) do
    [user.id, user.email, user.name, to_string(user.inserted_at)]
  end

  @impl true
  def query(account_id) do
    from u in User, where: u.organization_id == ^account_id
  end
end

Then use it:

HawkEx.CSV.export(account, MyApp.CSV.Formatters.Users)

Summary

Callbacks

Returns the header row for the CSV file.

Returns an Ecto query scoped to the given account_id.

Converts a single query result into a list of CSV values.

Callbacks

headers()

@callback headers() :: [String.t()]

Returns the header row for the CSV file.

query(account_id)

@callback query(account_id :: binary()) :: Ecto.Query.t()

Returns an Ecto query scoped to the given account_id.

The query result is passed row by row to to_row/1.

to_row(struct)

@callback to_row(struct()) :: [term()]

Converts a single query result into a list of CSV values.

Values may be strings, numbers, booleans, or nil. The exporter handles CSV escaping and string conversion.