From f4d71b4d9fb4191c07a9c200d32626175568b4fa Mon Sep 17 00:00:00 2001 From: Birte Kristina Friesel Date: Sat, 26 Aug 2023 09:17:28 +0200 Subject: obtain autocompletion from database --- lib/Travelynx.pm | 1 + lib/Travelynx/Controller/Api.pm | 18 ++++++++++++++++++ lib/Travelynx/Model/Stations.pm | 13 +++++++++++++ 3 files changed, 32 insertions(+) (limited to 'lib') diff --git a/lib/Travelynx.pm b/lib/Travelynx.pm index 8437686..39eca59 100755 --- a/lib/Travelynx.pm +++ b/lib/Travelynx.pm @@ -2397,6 +2397,7 @@ sub startup { $r->get( '/p/:name/j/:id' => 'public_journey' ) ->to('profile#journey_details'); $r->get('/.well-known/webfinger')->to('account#webfinger'); + $r->get('/dyn/:av/autocomplete.js')->to('api#autocomplete'); $r->post('/api/v1/import')->to('api#import_v1'); $r->post('/api/v1/travel')->to('api#travel_v1'); $r->post('/action')->to('traveling#travel_action'); diff --git a/lib/Travelynx/Controller/Api.pm b/lib/Travelynx/Controller/Api.pm index 7f72a53..687243d 100755 --- a/lib/Travelynx/Controller/Api.pm +++ b/lib/Travelynx/Controller/Api.pm @@ -7,6 +7,7 @@ use Mojo::Base 'Mojolicious::Controller'; use DateTime; use List::Util; +use Mojo::JSON qw(encode_json); use UUID::Tiny qw(:std); # Internal Helpers @@ -648,4 +649,21 @@ sub set_token { $self->redirect_to('account'); } +sub autocomplete { + my ($self) = @_; + + $self->res->headers->cache_control('max-age=86400, immutable'); + + my $output + = "document.addEventListener('DOMContentLoaded',function(){M.Autocomplete.init(document.querySelectorAll('.autocomplete'),{\n"; + $output .= 'minLength:3,limit:50,data:'; + $output .= encode_json( $self->stations->get_for_autocomplete ); + $output .= "\n});});\n"; + + $self->render( + format => 'js', + data => $output + ); +} + 1; diff --git a/lib/Travelynx/Model/Stations.pm b/lib/Travelynx/Model/Stations.pm index 75b4174..ecd8adb 100644 --- a/lib/Travelynx/Model/Stations.pm +++ b/lib/Travelynx/Model/Stations.pm @@ -50,6 +50,19 @@ sub add_or_update { ); } +sub get_for_autocomplete { + my ($self) = @_; + + my $res = $self->{pg}->db->select( 'stations', ['name'] ); + my %ret; + + while ( my $row = $res->hash ) { + $ret{ $row->{name} } = undef; + } + + return \%ret; +} + # Fast sub get_by_eva { my ( $self, $eva, %opt ) = @_; -- cgit v1.2.3