+
+ def set_cache(%Object{data: %{"id" => ap_id}} = object) do
+ Cachex.put(:object_cache, "object:#{ap_id}", object)
+ {:ok, object}
+ end
+
+ def update_and_set_cache(changeset) do
+ with {:ok, object} <- Repo.update(changeset) do
+ set_cache(object)
+ end
+ end
+
+ def increase_replies_count(ap_id) do
+ Object
+ |> where([o], fragment("?->>'id' = ?::text", o.data, ^to_string(ap_id)))
+ |> update([o],
+ set: [
+ data:
+ fragment(
+ """
+ jsonb_set(?, '{repliesCount}',
+ (coalesce((?->>'repliesCount')::int, 0) + 1)::varchar::jsonb, true)
+ """,
+ o.data,
+ o.data
+ )
+ ]
+ )
+ |> Repo.update_all([])
+ |> case do
+ {1, [object]} -> set_cache(object)
+ _ -> {:error, "Not found"}
+ end
+ end
+
+ def decrease_replies_count(ap_id) do
+ Object
+ |> where([o], fragment("?->>'id' = ?::text", o.data, ^to_string(ap_id)))
+ |> update([o],
+ set: [
+ data:
+ fragment(
+ """
+ jsonb_set(?, '{repliesCount}',
+ (greatest(0, (?->>'repliesCount')::int - 1))::varchar::jsonb, true)
+ """,
+ o.data,
+ o.data
+ )
+ ]
+ )
+ |> Repo.update_all([])
+ |> case do
+ {1, [object]} -> set_cache(object)
+ _ -> {:error, "Not found"}
+ end
+ end
+
+ def increase_vote_count(ap_id, name) do
+ with %Object{} = object <- Object.normalize(ap_id),
+ "Question" <- object.data["type"] do
+ multiple = Map.has_key?(object.data, "anyOf")
+
+ options =
+ (object.data["anyOf"] || object.data["oneOf"] || [])
+ |> Enum.map(fn
+ %{"name" => ^name} = option ->
+ Kernel.update_in(option["replies"]["totalItems"], &(&1 + 1))
+
+ option ->
+ option
+ end)
+
+ data =
+ if multiple do
+ Map.put(object.data, "anyOf", options)
+ else
+ Map.put(object.data, "oneOf", options)
+ end
+
+ object
+ |> Object.change(%{data: data})
+ |> update_and_set_cache()
+ else
+ _ -> :noop
+ end
+ end