]> git.ktnx.net Git - lsl.git/blob - lib/App/LazyShoppingList/API.pm
move sub declaration before usage
[lsl.git] / lib / App / LazyShoppingList / API.pm
1 use v5.26;
2 use warnings;
3 use utf8;
4
5 package App::LazyShoppingList::API;
6 use Dancer2;
7 use Exporter qw(import);
8
9 our $VERSION = '0.1';
10
11 our @EXPORT = qw( &get_database &get_lists_version &increment_lists_version
12     &invalid_input exception );
13
14 use Dancer2::Plugin::DBIC;
15
16 use experimental 'signatures';
17
18 my %fixed_db_settings = (
19     RaiseError => 1,
20     AutoCommit => 1,
21     PrintError => 0,
22 );
23 #my @on_db_connect_do = (
24 #    "SET NAMES 'utf8'",
25 #);
26 #
27 #hook database_connected => sub {
28 #    my $dbh = shift;
29 #
30 #    $dbh->do($_) for @on_db_connect_do;
31 #};
32
33 sub get_database {
34     $ENV{DBIC_TRACE}=1;
35     my %cfg = %{ config->{db} };
36     DBICx::Sugar::config( { default => \%cfg } );
37     $cfg{schema_class} = 'App::LazyShoppingList::Schema';
38     while(my($k,$v) = each %fixed_db_settings ) {
39         $cfg{options}{$k} = $v;
40     }
41     my $dbh = DBICx::Sugar::schema();
42
43     warn to_json(DBICx::Sugar::get_config());
44
45     $dbh->connect;
46
47     return $dbh;
48 }
49
50 sub get_lists_version($dbh) {
51     my $g = $dbh->resultset('Globals')->single;
52     return  $g->lists_version;
53 }
54
55 sub increment_lists_version($dbh) {
56     $dbh->storage->dbh_do(
57         sub {
58             my ( $storage, $dbh ) = @_;
59             $dbh->do(
60                 'UPDATE globals SET lists_version = lists_version + 1');
61         }
62     );
63
64     my $g = $dbh->resultset('Globals')->single;
65     return $g->lists_version;
66 }
67
68 sub exception($http_code, $text) {
69     status $http_code;
70     return { exception => $text };
71 }
72
73 sub invalid_input($details = undef) {
74     return exception 400,
75         "Invalid input" . ( defined($details) ? " ($details)" : '' );
76 }
77
78
79 1;