937 B · text History e569b6d
defmodule CartosnapAppWeb.Api.V1.TripController do
  @moduledoc """
  `GET /api/v1/trips`: the trips the user can add photos to (their own and
  those they're a member of), newest first, for the app's trip picker.
  """
  use CartosnapAppWeb, :controller

  alias CartosnapApp.Accounts
  alias CartosnapApp.Trips

  def index(conn, _params) do
    scope = conn.assigns.current_scope
    trips = Trips.list_trips(scope)
    summaries = Trips.trip_summaries(trips)
    owners = trips |> Enum.map(& &1.user) |> Accounts.display_names()

    json(conn, %{
      trips:
        for trip <- trips do
          %{
            id: trip.id,
            name: trip.name,
            date_start: trip.date_start,
            date_end: trip.date_end,
            owned: trip.user == scope.user.id,
            owner_name: owners[trip.user],
            photo_count: get_in(summaries, [trip.id, :count]) || 0
          }
        end
    })
  end
end