App-Jiffy

 view release on metacpan or  search on metacpan

lib/App/Jiffy/TimeEntry.pm  view on Meta::CPAN

  my $client = MongoDB::MongoClient->new;
  my $entry  = $client->get_database( $cfg->{db} )->get_collection($collection)
    ->find_one( { _id => $_id } );
  return unless $entry;
  return App::Jiffy::TimeEntry->new(
    id         => $entry->{_id},
    title      => $entry->{title},
    start_time => $entry->{start_time},
    cfg        => $cfg,
  );
}

=head2 search C<$config> C<%options>...

C<search> will return an array of TimeEntry that fit the given C<%options>.

C<%options> can include the following:

=over

=item C<query>

This is the query syntax available via L<MongoDB::Collection>.

=item C<sort>

If present, the results will be sorted via the hashref given by this option.

=item C<limit>

If present, the results will limited to the number provided.

=back

=cut

sub search {
  my $cfg     = shift;
  my %options = @_;
  my $query   = $options{query};
  my $sort    = $options{sort};
  my $limit   = $options{limit};

  my $client  = MongoDB::MongoClient->new;
  my $entries = $client->get_database( $cfg->{db} )->get_collection($collection)
    ->find($query);

  if ($sort) {
    $entries = $entries->sort($sort);
  }

  if ($limit) {
    $entries = $entries->limit($limit);
  }

  # Return undef if nothing was found
  return unless $entries;

  my $LocalTZ = DateTime::TimeZone->new( name => 'local' );    # For caching

# @TODO create a subclass of the MongoDB cursor that allows chaining of results like MongoDB
  map {
    $_->{start_time}->set_time_zone($LocalTZ);    # Convert to local tz
    App::Jiffy::TimeEntry->new(
      id         => $_->{_id},
      title      => $_->{title},
      start_time => $_->{start_time},
      cfg        => $cfg,
      )
  } $entries->all;
}

=head2 last_entry

C<last_entry> will return the last TimeEntry in the db.

=cut

sub last_entry {
  my $cfg = shift;

  my $client = MongoDB::MongoClient->new;
  my $entry  = $client->get_database( $cfg->{db} )->get_collection($collection)
    ->find->sort( { start_time => -1 } )->limit(1)->next;
  return unless $entry;
  return App::Jiffy::TimeEntry->new(
    id         => $entry->{_id},
    title      => $entry->{title},
    start_time => $entry->{start_time},
    cfg        => $cfg,
  );
}

=head2 TO_JSON

C<TO_JSON> will return the entry as a JSON convertible hash.

=cut

sub TO_JSON {
  my $self = shift;

  {
    start_time => $self->start_time->iso8601,
    title      => $self->title,
    duration   => { $self->duration->deltas },
  };
}

1;



( run in 0.422 second using v1.01-cache-2.11-cpan-63c85eba8c4 )