Pattern matching controller endpoints

Hello,

I am currently developing two endpoints to serve some information. My end goal is to use pattern matching to have the endpoint use a certain method based on the params passed in. If there is a param image_stats passed in I’d like for it to use the one Campaign object that contains said param.

def stats(conn, %{"owner_id" => owner_id, "campaign_id" => campaign_id}) do
    requested_fields = conn.assigns.jsonapi_query.fields["campaign_stats"] || []

    campaign_stats =
      %Campaign{owner_id: owner_id, id: campaign_id}
      |> CampaignStats.load(requested_fields)

    conn
    |> put_view(CampaignStatsView)
    |> render("show.json", %{data: campaign_stats})
  end

  def stats(conn, %{"owner_id" => owner_id, "campaign_id" => campaign_id, "image_stats" => image_stats }) do
    require IEx; IEx.pry
    requested_fields = conn.assigns.jsonapi_query.fields["campaign_stats"] || []

    campaign_stats =
      %Campaign{owner_id: owner_id, id: campaign_id, image_stats: image_stats}
      |> CampaignStats.load(requested_fields)

    conn
    |> put_view(CampaignStatsView)
    |> render("show.json", %{data: campaign_stats})
  end

I have a pry in the once I want it to hit, however it hits the one without the param above it and throws an error. How can I use pattern matching to make this happen? I come from Ruby so learning the pattern matching has been a slight learning curve and can’t seem to figure this one out.

the order in which you define the versions of your stats function matter, try moving the definition with more constraints first

1 Like

Could have sworn I tried moving the methods around but I guess not. Works! Thanks a lot.