| 1 | package Data::CouchDB::Handler; | ||
| 2 | |||
| 3 | use Moose; | ||
| 4 | |||
| 5 | our $VERSION = '0.14'; | ||
| 6 | |||
| 7 | use Data::CouchDB; | ||
| 8 | use YAML::XS; | ||
| 9 | use feature 'state'; | ||
| 10 | |||
| 11 | has couchdb_databases => ( | ||
| 12 | is => 'rw', | ||
| 13 | isa => 'HashRef', | ||
| 14 | #default => sub { {} }, | ||
| 15 | ); | ||
| 16 | |||
| 17 | sub couchdb { | ||
| 18 | my $self = shift; | ||
| 19 | my $db = shift; | ||
| 20 | my $ua = shift; | ||
| 21 | my $db_name = $self->couchdb_databases->{$db} || $db; | ||
| 22 | |||
| 23 | if ($ua or not defined $self->_couch_cache->{$db_name}) { | ||
| 24 | my $params = $self->_build_couchdb_params($db_name); | ||
| 25 | |||
| 26 | # For normal usage we dont expect to pass ua(user_agent). | ||
| 27 | # So dont cache if ua is passed. | ||
| 28 | if ($ua) { | ||
| 29 | $params->{ua} = $ua; | ||
| 30 | return Data::CouchDB->new(%$params); | ||
| 31 | } | ||
| 32 | |||
| 33 | $self->_couch_cache->{$db_name} = Data::CouchDB->new(%$params); | ||
| 34 | } | ||
| 35 | |||
| 36 | return $self->_couch_cache->{$db_name}; | ||
| 37 | } | ||
| 38 | |||
| 39 | has couchdb => ( | ||
| 40 | is => 'ro', | ||
| 41 | reader => '_couchdb_configuration' | ||
| 42 | ); | ||
| 43 | |||
| 44 | sub _build_couchdb_params { | ||
| 45 | my $self = shift; | ||
| 46 | my $db_name = shift; | ||
| 47 | |||
| 48 | my $params->{db} = $db_name; | ||
| 49 | |||
| 50 | state $config = YAML::XS::LoadFile('/etc/couchdb.yml'); | ||
| 51 | if ($config->{master}->{ip} ne '127.0.0.1') { | ||
| 52 | $params->{master_host} = $config->{master}->{ip}; | ||
| 53 | $params->{master_port} = 6984; | ||
| 54 | $params->{master_protocol} = 'https://'; | ||
| 55 | } | ||
| 56 | $params->{couchdb} = $config->{password}; | ||
| 57 | |||
| 58 | return $params; | ||
| 59 | } | ||
| 60 | |||
| 61 | has '_couch_cache' => ( | ||
| 62 | is => 'ro', | ||
| 63 | isa => 'HashRef', | ||
| 64 | default => sub { {}; }, | ||
| 65 | ); | ||
| 66 | |||
| 67 | __PACKAGE__->meta->make_immutable; | ||
| 68 | |||
| 69 | 1; | ||
| 70 |