Created
February 20, 2016 06:40
-
-
Save hansonkd/921318640545fafe9b83 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
-module(example_hook). | |
-export([postcommit/1]). | |
postcommit(RObj) -> | |
{ok, Client} = riak:local_client(), | |
ThisNode = atom_to_binary(node(), latin1), | |
UserKey = riak_object:key(RObj), | |
% The Users value from a riak_dt_map (Map) | |
{{_, UserMap},_} = riak_kv_crdt:value(RObj, riak_dt_map), | |
HistoryBucket = {<<"histories">>, <<"users">>}, | |
% Get the history for our User, create it if it doesn't exist | |
{HistoryObj, HistoryVal, HistoryCtx} = case Client:get(HistoryBucket, UserKey) of | |
{error, notfound} -> | |
Obj = riak_kv_crdt:new(HistoryBucket, UserKey, riak_dt_map), | |
{Obj, [], undefined}; | |
{ok, Obj} -> | |
% The datatype update requires the context if the value exists | |
{{HistCtx, HistVal}, _} = riak_kv_crdt:value(Obj, riak_dt_map), | |
{Obj, HistVal, HistCtx} | |
end, | |
error_logger:info_msg("Updating History for ~p ~n", [UserKey]), | |
error_logger:info_msg("Users value: ~p ~n", [UserMap]), | |
error_logger:info_msg("Users history before update: ~p ~n", [HistoryVal]), | |
% Increment the number of commits | |
UpdateNumCommits = [{update,{<<"num_commits">>,riak_dt_emcntr},increment}], | |
% Look up the email on the current commit and add to a set of all past email values | |
UpdateEmail = case proplists:get_value({<<"email">>,riak_dt_lwwreg}, UserMap) of | |
undefined -> []; | |
UserEmail -> [{update,{<<"all_emails">>,riak_dt_orswot}, {add, UserEmail}}] | |
end, | |
UpdateOp = {crdt_op, riak_dt_map, {update, UpdateNumCommits ++ UpdateEmail}, HistoryCtx}, | |
NewHistory = riak_kv_crdt:update(HistoryObj, ThisNode, UpdateOp), | |
Client:put(NewHistory), | |
RObj. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment