Separating of Storage context
This commit is contained in:
15
lib/mobilizon/storage/ecto.ex
Normal file
15
lib/mobilizon/storage/ecto.ex
Normal file
@@ -0,0 +1,15 @@
|
||||
defmodule Mobilizon.Storage.Ecto do
|
||||
@moduledoc """
|
||||
Mobilizon Ecto utils
|
||||
"""
|
||||
|
||||
import Ecto.Query, warn: false
|
||||
|
||||
@doc """
|
||||
Adds sort to the query.
|
||||
"""
|
||||
@spec sort(Ecto.Query.t(), atom, atom) :: Ecto.Query.t()
|
||||
def sort(query, sort, direction) do
|
||||
from(query, order_by: [{^direction, ^sort}])
|
||||
end
|
||||
end
|
||||
48
lib/mobilizon/storage/page.ex
Normal file
48
lib/mobilizon/storage/page.ex
Normal file
@@ -0,0 +1,48 @@
|
||||
defmodule Mobilizon.Storage.Page do
|
||||
@moduledoc """
|
||||
Module for pagination of queries.
|
||||
"""
|
||||
|
||||
import Ecto.Query
|
||||
|
||||
alias Mobilizon.Storage.Repo
|
||||
|
||||
defstruct [
|
||||
:total,
|
||||
:elements
|
||||
]
|
||||
|
||||
@type t :: %__MODULE__{
|
||||
total: integer,
|
||||
elements: struct
|
||||
}
|
||||
|
||||
@doc """
|
||||
Returns a Page struct for a query.
|
||||
"""
|
||||
@spec build_page(Ecto.Query.t(), integer | nil, integer | nil) :: t
|
||||
def build_page(query, page, limit) do
|
||||
[total, elements] =
|
||||
[
|
||||
fn -> Repo.aggregate(query, :count, :id) end,
|
||||
fn -> Repo.all(paginate(query, page, limit)) end
|
||||
]
|
||||
|> Enum.map(&Task.async/1)
|
||||
|> Enum.map(&Task.await/1)
|
||||
|
||||
%__MODULE__{total: total, elements: elements}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Add limit and offset to the query.
|
||||
"""
|
||||
@spec paginate(Ecto.Query.t() | struct, integer | nil, integer | nil) :: Ecto.Query.t()
|
||||
def paginate(query, page \\ 1, size \\ 10)
|
||||
|
||||
def paginate(query, page, _size) when is_nil(page), do: paginate(query)
|
||||
def paginate(query, page, size) when is_nil(size), do: paginate(query, page)
|
||||
|
||||
def paginate(query, page, size) do
|
||||
from(query, limit: ^size, offset: ^((page - 1) * size))
|
||||
end
|
||||
end
|
||||
5
lib/mobilizon/storage/postgrex_types.ex
Normal file
5
lib/mobilizon/storage/postgrex_types.ex
Normal file
@@ -0,0 +1,5 @@
|
||||
Postgrex.Types.define(
|
||||
Mobilizon.Storage.PostgresTypes,
|
||||
[Geo.PostGIS.Extension | Ecto.Adapters.Postgres.extensions()],
|
||||
json: Jason
|
||||
)
|
||||
16
lib/mobilizon/storage/repo.ex
Normal file
16
lib/mobilizon/storage/repo.ex
Normal file
@@ -0,0 +1,16 @@
|
||||
defmodule Mobilizon.Storage.Repo do
|
||||
@moduledoc """
|
||||
Mobilizon Repo.
|
||||
"""
|
||||
|
||||
use Ecto.Repo,
|
||||
otp_app: :mobilizon,
|
||||
adapter: Ecto.Adapters.Postgres
|
||||
|
||||
@doc """
|
||||
Dynamically loads the repository url from the DATABASE_URL environment variable.
|
||||
"""
|
||||
def init(_, opts) do
|
||||
{:ok, Keyword.put(opts, :url, System.get_env("DATABASE_URL"))}
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user