| 1 | package Telebot::Plugin::DB; | ||
| 2 | |||
| 3 | use Mojo::Base 'Mojolicious::Plugin', -signatures; | ||
| 4 | use Mojo::Pg; | ||
| 5 | |||
| 6 | has [qw(app connection dbh)]; | ||
| 7 | |||
| 8 | sub register ($self, $app, $conf) { | ||
| 9 | $self->app($app); | ||
| 10 | $self->connection($conf->{connection} || $app->config->{connection}); | ||
| 11 | |||
| 12 | $app->helper('connect.dbh' => sub { | ||
| 13 | my ($c) = @_; | ||
| 14 | die "Connection not found" if !$self->connection; | ||
| 15 | if (!$self->dbh || !$self->dbh->db->ping) { | ||
| 16 | $self->dbh(Mojo::Pg->new($self->connection)); | ||
| 17 | } | ||
| 18 | $self->dbh; | ||
| 19 | }); | ||
| 20 | $app->helper('connect.db' => sub { | ||
| 21 | shift->connect->dbh->db; | ||
| 22 | }); | ||
| 23 | $self; | ||
| 24 | } | ||
| 25 | |||
| 26 | 1; | ||
| 27 | |||
| 28 | =pod | ||
| 29 | |||
| 30 | =encoding utf8 | ||
| 31 | |||
| 32 | =head1 NAME | ||
| 33 | |||
| 34 | Telebot::Plugin::DB - Helpers for work with database. | ||
| 35 | |||
| 36 | =head1 SYNOPSIS | ||
| 37 | |||
| 38 | my $dbh = $app->connect->dbh; | ||
| 39 | $dbh->db->select('messages', '*'); | ||
| 40 | |||
| 41 | my $db = $app->connect->db; | ||
| 42 | $db->select('messages', '*'); | ||
| 43 | |||
| 44 | =head1 DESCRIPTION | ||
| 45 | |||
| 46 | L<Telebot::Plugin::DB> - plugin with some helpers for work with database. | ||
| 47 | |||
| 48 | =head1 HELPERS | ||
| 49 | |||
| 50 | L<Telebot::Plugin::DB> implements the following helpers. | ||
| 51 | |||
| 52 | =head2 connect->dbh | ||
| 53 | |||
| 54 | Connects to database and returns instance to Mojo::Pg | ||
| 55 | |||
| 56 | =head2 connect->db | ||
| 57 | |||
| 58 | Connects to database and returns instance to Mojo::Pg->db | ||
| 59 | |||
| 60 | =head1 METHODS | ||
| 61 | |||
| 62 | L<Telebot::Plugin::DB> inherits all methods from L<Mojolicious::Plugin> and implements the following new ones. | ||
| 63 | |||
| 64 | =head2 register | ||
| 65 | |||
| 66 | my $tg = $plugin->register(Mojolicious->new); | ||
| 67 | |||
| 68 | Register plugin in Mojolicious application and define helpers. | ||
| 69 | |||
| 70 | =head1 COPYRIGHT AND LICENSE | ||
| 71 | |||
| 72 | Copyright (C) 2022, Igor Lobanov. | ||
| 73 | This program is free software, you can redistribute it and/or modify it under the terms of the Artistic License version | ||
| 74 | 2.0. | ||
| 75 | |||
| 76 | =head1 SEE ALSO | ||
| 77 | |||
| 78 | L<https://github.com/igorlobanov/telebot>, L<Mojolicious::Guides>, L<https://mojolicious.org>, | ||
| 79 | L<https://core.telegram.org/bots/api>. | ||
| 80 | |||
| 81 | =cut |