| 1 | package MojoX::Session::Store::MongoDB; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use base 'MojoX::Session::Store'; | ||
| 7 | use MongoDB; | ||
| 8 | use Carp qw(croak); | ||
| 9 | |||
| 10 | use namespace::clean; | ||
| 11 | |||
| 12 | __PACKAGE__->attr('mongodb'); | ||
| 13 | __PACKAGE__->attr('mongodb_coll'); | ||
| 14 | |||
| 15 | our $VERSION = '0.52'; | ||
| 16 | |||
| 17 | sub new { | ||
| 18 | my ($class, $param) = @_; | ||
| 19 | my $self = $class->SUPER::new(); | ||
| 20 | bless $self, $class; | ||
| 21 | |||
| 22 | $param ||= {}; | ||
| 23 | my $database = delete $param->{database}; | ||
| 24 | my $collection = delete $param->{collection}; | ||
| 25 | croak "database and collection parameters required" | ||
| 26 | unless ($database or $param->{mongodb}) and $collection; | ||
| 27 | |||
| 28 | $self->mongodb($param->{mongodb} || MongoDB::Connection->new($param)->get_database($database)); | ||
| 29 | $self->mongodb_coll($self->mongodb->get_collection($collection)); | ||
| 30 | |||
| 31 | return $self; | ||
| 32 | } | ||
| 33 | |||
| 34 | sub create { | ||
| 35 | my ($self, $sid, $expires, $data) = @_; | ||
| 36 | |||
| 37 | my $new_data = { | ||
| 38 | _id => $sid, | ||
| 39 | data => $data, | ||
| 40 | expires => $expires, | ||
| 41 | }; | ||
| 42 | $self->mongodb_coll->update({_id => $sid}, $new_data, {upsert => 1}); | ||
| 43 | my $err = $self->mongodb->last_error; | ||
| 44 | if ($err->{err}) { | ||
| 45 | require Data::Dumper; | ||
| 46 | warn Data::Dumper::Dumper($err); | ||
| 47 | return 0; | ||
| 48 | } | ||
| 49 | else { | ||
| 50 | return 1; | ||
| 51 | } | ||
| 52 | } | ||
| 53 | |||
| 54 | sub update { | ||
| 55 | shift->create(@_); | ||
| 56 | } | ||
| 57 | |||
| 58 | sub load { | ||
| 59 | my ($self, $sid) = @_; | ||
| 60 | my $res = $self->mongodb_coll->find_one({_id => $sid}); | ||
| 61 | return ($res->{expires}, $res->{data}); | ||
| 62 | } | ||
| 63 | |||
| 64 | sub delete { | ||
| 65 | my ($self, $sid) = @_; | ||
| 66 | my $res = $self->mongodb_coll->remove({_id => $sid}); | ||
| 67 | return 1; | ||
| 68 | } | ||
| 69 | |||
| 70 | 1; | ||
| 71 | __END__ |