jsonld-ex/lib/json/ld/node_identifier_map.ex
Marcel Otto 2405d7d32b json_ld: JSON-LD flattening algorithm
lists not working yet; requires a major modification of the specified algorithm, since we can't fill lists by reference in Elixir
2017-03-18 21:52:41 +01:00

51 lines
1.1 KiB
Elixir

defmodule JSON.LD.NodeIdentifierMap do
@moduledoc nil
use GenServer
import JSON.LD
# Client API
def start_link(opts \\ []) do
GenServer.start_link(__MODULE__, :ok, opts)
end
def stop(pid, reason \\ :normal, timeout \\ :infinity) do
GenServer.stop(pid, reason, timeout)
end
@doc """
Generate Blank Node Identifier
Details at <https://www.w3.org/TR/json-ld-api/#generate-blank-node-identifier>
"""
def generate_blank_node_id(pid, identifier \\ nil) do
GenServer.call(pid, {:generate_id, identifier})
end
# Server Callbacks
def init(:ok) do
{:ok, %{map: %{}, counter: 0}}
end
def handle_call({:generate_id, identifier}, _, %{map: map, counter: counter} = state) do
if identifier && (mapped_identifier = map[identifier]) do
{:reply, mapped_identifier, state}
else
blank_node_id = "_:b#{counter}"
{:reply, blank_node_id, %{
counter: counter + 1,
map:
if identifier do
Map.put(map, identifier, blank_node_id)
else
map
end
}}
end
end
end