8 use Digest::MD5 qw(md5_hex);
9 use Data::Dump qw(dump);
12 my ($class, $host, $port, $options) = @_;
14 my $ua = LWP::UserAgent->new;
19 $ua->add_handler("request_send", sub { shift->dump; return });
20 $ua->add_handler("response_done", sub { shift->dump; return });
27 base_uri => "http://$host:$port/",
31 sub ua { shift->{ua} }
32 sub base { shift->{base_uri} }
35 my ($self, $method, $uri, $content) = @_;
37 my $full_uri = $self->base . $uri;
40 if (defined $content) {
41 #Content-Type: application/json
43 $req = HTTP::Request->new( $method, $full_uri, undef, encode_json $content );
44 $req->header('Content-Type' => 'application/json');
46 $req = HTTP::Request->new( $method, $full_uri );
49 my $response = $self->ua->request($req);
51 if ($response->is_success) {
52 return decode_json $response->content;
54 die($response->status_line . ":" . $response->content);
59 my ($self, $url) = @_;
61 $self->request(DELETE => $url);
65 my ($self, $url) = @_;
68 $self->request(GET => $url);
72 my ($self, $url, $json) = @_;
75 $self->request(PUT => $url, $json);
79 my ($self, $url, $json) = @_;
81 $self->request(POST => $url, $json);
85 my ($self, $url, $json) = @_;
87 warn "# update_doc $url";
89 my $json_md5 = md5_hex encode_json $json;
90 $json->{x_sync}->{json_md5} = $json_md5;
92 if ( my $old = eval { $self->get( $url ) } ) {
93 warn "# old ", $old->{_rev}; #dump($old);
95 if ( $json_md5 ne $old->{x_sync}->{json_md5} ) {
96 $json->{_rev} = $old->{_rev};
97 warn :"# update $url";
98 $self->put( $url => $json );
100 warn "# unchanged $url";
103 warn "# insert $url ", dump($json);
104 $self->put( $url => $json );