Last active
October 13, 2018 00:24
-
-
Save smathy/739411c90934252e6f945f15cd29f2ae to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Snug.Repo do | |
alias Snug.Neo | |
@var "n" | |
def all mod do | |
Neo.query!(""" | |
MATCH (#{@var}:#{class_name mod}) | |
RETURN #{@var} | |
""") | |
|> Enum.map(&(convert( &1, mod))) | |
end | |
def get! mod, id do | |
%{id: id} | |
|> Neo.query!(""" | |
MATCH (#{@var}:#{class_name mod}) | |
WHERE id(#{@var}) = $id | |
RETURN #{@var} | |
""") | |
|> List.first | |
|> convert(mod) | |
end | |
def insert changeset do | |
mod = changeset.data.__struct__ | |
%{ changes: changeset.changes } | |
|> Neo.query!(""" | |
CREATE (#{@var}:#{class_name mod} $changes) | |
SET | |
#{@var}.inserted_at = timestamp(), | |
#{@var}.updated_at = timestamp() | |
RETURN #{@var} | |
""") | |
|> List.first | |
|> convert(mod) | |
end | |
defp convert %{ @var => %{ id: id, properties: properties } }, mod do | |
struct( mod, Map.merge( ExUtils.Map.atomize_keys(properties), %{ id: id } ) ) | |
end | |
defp class_name mod do | |
mod | |
|> ExUtils.Module.name | |
|> String.split(".") | |
|> List.last | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment