Merge branch 'feature/fix-warnings' into 'develop'
[akkoma] / lib / pleroma / object.ex
1 defmodule Pleroma.Object do
2 use Ecto.Schema
3 alias Pleroma.{Repo, Object}
4 import Ecto.{Query, Changeset}
5
6 schema "objects" do
7 field :data, :map
8
9 timestamps()
10 end
11
12 def create(data) do
13 Object.change(%Object{}, %{data: data})
14 |> Repo.insert
15 end
16
17 def change(struct, params \\ %{}) do
18 struct
19 |> cast(params, [:data])
20 |> validate_required([:data])
21 |> unique_constraint(:ap_id, name: :objects_unique_apid_index)
22 end
23
24 def get_by_ap_id(nil), do: nil
25 def get_by_ap_id(ap_id) do
26 Repo.one(from object in Object,
27 where: fragment("(?)->>'id' = ?", object.data, ^ap_id))
28 end
29
30 def get_cached_by_ap_id(ap_id) do
31 if Mix.env == :test do
32 get_by_ap_id(ap_id)
33 else
34 key = "object:#{ap_id}"
35 Cachex.get!(:user_cache, key, fallback: fn(_) ->
36 object = get_by_ap_id(ap_id)
37 if object do
38 {:commit, object}
39 else
40 {:ignore, object}
41 end
42 end)
43 end
44 end
45
46 def context_mapping(context) do
47 Object.change(%Object{}, %{data: %{"id" => context}})
48 end
49 end