Search code examples
perlmojoliciousmojolicious-lite

hypnotoad helper function in mojolicious lite


the Mojolicious::Lite app is working with morbo but not working with hypnotoad.

my $dbh = DBI->connect("dbi:mysql:dbname=xxx", "uname", "pass",
    { AutoCommit =>  0, mysql_enable_utf8 => 1},  )
    or die "Couldn't connect to database: ", $DBI::errstr;

helper db => sub { $dbh };
get '/xxx' => sub {
    my $sth = $self->db->prepare("insert into posts values(?,?,?,?,?,?)");
    $sth->execute('xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx');
    $sth->finish();
    $self->db->commit;
};

when run with hypnotoad, rest of the app is working but it is not reading/writing data to/from database. please help me write code that work with hypnotoad


Solution

  • You can use DBIx::Connector, like this

    use strict;
    use warnings;
    use Mojolicious::Lite;
    use DBIx::Connector;
    
    helper connector => sub { 
        state $db = DBIx::Connector->new(sprintf('dbi:mysql:host=%s:database=%s',@{  $config->{mysql_database}}{qw[host db]}),@{$config->{mysql_database}}{qw[user password]}) or die "Could not connect";
    };
    
    helper mysql => sub { shift->connector->dbh };
    
    post '/login' => sub {
        my $c = shift;
    
        my $user = $c->param('user_email');
        my $password = $c->param('password');
    
        my $sth = $c->mysql->prepare_cached('SELECT * FROM users WHERE user_email = ?') or $c->app->log->debug($DBI::errstr);
    
        $sth->execute($user);
    
        my $row = $sth->fetchrow_arrayref;
    
        $sth->finish;
    
        ## more code
    };