anchor.diff:  -export([write_json/2]).
   -export([delete_resource/2]).
   
  --record(state, {path, segments, hash, hashes, etag, mode}).
  +-record(state, {path, segments, hash, hashes, etag, mode, access}).
   
   init(_Transport, _Req, _Opts) ->
       {upgrade, protocol, cowboy_rest}.
  
positive.code: allowed_methods(Req, State) ->
      {[<<"GET">>, <<"PUT">>, <<"DELETE">>], Req, State}.
  
  forbidden(Req, State) ->
      {Token, Req0} = cowboy_req:cookie(<<"token">>, Req),
      case Token of
          undefined ->
  
negative.code: segments_to_hprops(Segments) ->
      lists:append(lists:foldl(fun({expr, star}, R) -> [[] | R]; (Value, R) -> [[list_to_binary(integer_to_list(length(R))), Value] | R] end, [], Segments)).
  
  write_json(Req, #state{access = Access, mode = pointer, hash = undefined, path = Path, segments = Segments} = State) when Access =:= <<"rw">> ->
      {ok, Json, Req0} = cowboy_req:body(Req),
      {Props} = jiffy:decode(Json),
      Q = <<"insert into objects(hash,version,path,value) values (md5($1),0,hstore($2::text[]),hstore($3::text[]))">>,
      {ok, _} = cloudstore_pg:equery(cloudstore_pool, Q, [Path, segments_to_hprops(Segments), props_to_hprops(Props)]),
      {true, Req0, State};
  write_json(Req, #state{access = Access, mode = pointer, hash = Hash} = State) when Access =:= <<"rw">> ->
      {ok, Json, Req0} = cowboy_req:body(Req),
      {Props} = jiffy:decode(Json),
      HProps = lists:append([[Name, jiffy:encode(Value)] || {Name, Value} <- Props]),
      Q = <<"update objects set version=version+1,value=value||hstore($2::text[]) where hash=$1">>,
      {ok, _} = cloudstore_pg:equery(cloudstore_pool, Q, [Hash, HProps]),
      {true, Req0, State};
  write_json(Req, State) ->
      {ok, Req0} = cowboy_req:reply(403, Req),
      {halt, Req0, State}.
  
  delete_resource(Req, #state{access = Access, mode = pointer, hash = Hash} = State) when Access =:= <<"rw">> ->
      Q = <<"delete from objects where hash=$1">>,
      {ok, _} = cloudstore_pg:equery(cloudstore_pool, Q, [Hash]),
      {true, Req, State};
  delete_resource(Req, State) ->
      {ok, Req0} = cowboy_req:reply(403, Req),
      {halt, Req0, State}.
  