defmodule Wiki.Content do @moduledoc """ The Content context. """ import Ecto.Query, warn: false alias Wiki.Repo alias Wiki.Content.Page alias Wiki.Content.Upload @doc """ Returns the list of pages. ## Examples iex> list_pages() [%Page{}, ...] """ def list_pages(user) do Repo.all(from p in Page, where: p.user_id == ^user.id) end @doc """ Gets a single page. Raises `Ecto.NoResultsError` if the Page does not exist. ## Examples iex> get_page!(123) %Page{} iex> get_page!(456) ** (Ecto.NoResultsError) """ def get_page!(id), do: Repo.get!(Page, id) def get_page(id), do: Repo.get(Page, id) @doc """ Creates a page. ## Examples iex> create_page(%{field: value}) {:ok, %Page{}} iex> create_page(%{field: bad_value}) {:error, %Ecto.Changeset{}} """ def create_page(attrs \\ %{}) do %Page{} |> Page.changeset(attrs) |> Repo.insert() |> case do {:ok, page} -> content = Map.get(attrs, "content") || Map.get(attrs, :content) unless is_nil(content) do Page.update_page_links(%Page{page | content: content}) end {:ok, page} {:error, reason} -> {:error, reason} end end @doc """ Updates a page. ## Examples iex> update_page(page, %{field: new_value}) {:ok, %Page{}} iex> update_page(page, %{field: bad_value}) {:error, %Ecto.Changeset{}} """ def update_page(%Page{} = page, attrs) do page |> Page.changeset(attrs) |> Repo.update() |> case do {:ok, page} -> content = Map.get(attrs, "content") || Map.get(attrs, :content) unless is_nil(content) do Page.update_page_links(%Page{page | content: content}) end {:ok, page} {:error, reason} -> {:error, reason} end end @doc """ Deletes a page. ## Examples iex> delete_page(page) {:ok, %Page{}} iex> delete_page(page) {:error, %Ecto.Changeset{}} """ def delete_page(%Page{} = page) do Repo.delete(page) end @doc """ Returns an `%Ecto.Changeset{}` for tracking page changes. ## Examples iex> change_page(page) %Ecto.Changeset{data: %Page{}} """ def change_page(%Page{} = page, attrs \\ %{}, options \\ []) do Page.changeset(page, attrs, options) end def get_upload(%Page{id: page_id}, id) do get_upload(page_id, id) end def get_upload(page_id, upload_id) do Repo.one(from u in Upload, where: u.id == ^upload_id and u.page_id == ^page_id) end end