extract update to CouchDB to force update document
[ILL-Zotero-RT] / CouchDB.pm
index 8b13b36..9512174 100644 (file)
@@ -5,6 +5,8 @@ use warnings;
 
 use LWP::UserAgent;
 use JSON;
 
 use LWP::UserAgent;
 use JSON;
+use Digest::MD5 qw(md5_hex);
+use Data::Dump qw(dump);
 
 sub new {
   my ($class, $host, $port, $options) = @_;
 
 sub new {
   my ($class, $host, $port, $options) = @_;
@@ -74,4 +76,29 @@ sub post {
   $self->request(POST => $url, $json);
 }
 
   $self->request(POST => $url, $json);
 }
 
+sub update {
+       my ($self, $url, $json) = @_;
+
+       warn "# update_doc $url";
+
+       my $json_md5 = md5_hex encode_json $json;
+       $json->{x_sync}->{json_md5} = $json_md5;
+
+       if ( my $old = eval { $self->get( $url ) } ) {
+               warn "# old ", $old->{_rev}; #dump($old);
+
+               if ( $json_md5 ne $old->{x_sync}->{json_md5} ) {
+                       $json->{_rev} = $old->{_rev};
+                       warn :"# update $url";
+                       $self->put( $url => $json );
+               } else {
+                       warn "# unchanged $url";
+               }
+       } else {
+               warn "# insert $url ", dump($json);
+               $self->put( $url => $json );
+       }
+
+}
+
 1;
 1;