Debian Codegraph @

lemonldap-ng-common/lib/Lemonldap/NG/Common/PSGI/Router.pm

raw
1 package Lemonldap::NG::Common::PSGI::Router;
2
3 use strict;
4 use Mouse;
5 use Lemonldap::NG::Common::PSGI;
6 use Lemonldap::NG::Common::PSGI::Constants;
7
8 our $VERSION = '2.23.0';
9
10 extends 'Lemonldap::NG::Common::PSGI';
11
12 # Properties
13 has routes => (
14 is => 'rw',
15 isa => 'HashRef',
16 default =>
17 sub { { GET => {}, POST => {}, PUT => {}, PATCH => {}, DELETE => {} } }
18 );
19 has defaultRoute => ( is => 'rw', default => 'index.html' );
20
21 # Routes initialization
22
23 sub addRoute {
24 my ( $self, $word, $dest, $methods, $transform ) = (@_);
25 $methods ||= [qw(GET POST PUT PATCH DELETE)];
26 foreach my $method (@$methods) {
27 $self->logger->debug("Add $method route:");
28 $self->genRoute( $self->routes->{$method}, $word, $dest, $transform );
29 }
30 return $self;
31 }
32
33 sub genRoute {
34 my ( $self, $routes, $word, $dest, $transform ) = @_;
35 unless ( ref $routes eq 'HASH' ) {
36 $self->logger->error(
37 'Conflict detected between 2 extensions, aborting 1 route');
38 return;
39 }
40 if ( ref $word eq 'ARRAY' ) {
41 foreach my $w (@$word) {
42 $self->genRoute( $routes, $w, $dest, $transform );
43 }
44 }
45 else {
46 $dest //= $word;
47 if ( $word =~ /^:(.*)$/ ) {
48 $routes->{'#'} = $1;
49 die "Target required for $word" unless ($dest);
50 $word = ':';
51 }
52 elsif ( my ( $first, $rest ) = $word =~ m#^(.*?)/(.*)# ) {
53 return $self->genRoute( $routes->{$first},
54 $rest, $dest, $transform );
55 }
56 else {
57 $dest ||= $word;
58 }
59 if ( $word =~ /^(.+)\.html$/ and $word eq $dest ) {
60 my $tpl = $1 or die;
61 $self->logger->debug("route $dest will use $tpl");
62 $routes->{$word} = sub { $self->sendHtml( $_[1], $tpl ) };
63 return;
64 }
65 if ( $transform and ( not ref($dest) or ref($dest) eq 'CODE' ) ) {
66 $dest = $transform->($dest);
67 }
68 if ( my $t = ref $dest ) {
69 if ( $t eq 'HASH' ) {
70 $routes->{$word} ||= {};
71 foreach my $w ( keys %$dest ) {
72 $self->genRoute( $routes->{$word}, $w, $dest->{$w},
73 $transform );
74 }
75 return;
76 }
77 elsif ( $t eq 'ARRAY' ) {
78 $routes->{$word} ||= {};
79 foreach my $w ( @{$dest} ) {
80 $self->genRoute( $routes->{$word}, $w, $w, $transform );
81 }
82 return;
83 }
84 }
85 if ( $routes->{$word} ) {
86 eval { $self->logger->warn(qq'Route "$word" redefined'); };
87 }
88 if ( my $t = ref $dest ) {
89 if ( $t eq 'CODE' ) {
90 $routes->{$word} = $dest;
91 }
92 else {
93 die "Type $t unauthorized in routes";
94 }
95 }
96 elsif ( $self->can($dest) ) {
97 $routes->{$word} = sub { shift; $self->$dest(@_) };
98 }
99 else {
100 die "$dest() isn't a method";
101 }
102 $self->logger->debug("route $word added");
103 }
104 }
105
106 sub handlerAbort {
107 my ( $self, $path, $msg ) = @_;
108 delete $self->routes->{$path};
109 $self->addRoute(
110 $path => sub {
111 my ( $self, $req ) = @_;
112 return $self->sendError( $req, $msg, 500 );
113 }
114 );
115 }
116
117 # Methods that dispatch requests
118
119 sub handler {
120 my ( $self, $req ) = @_;
121
122 # Reinitialize configuration message
123 $Lemonldap::NG::Common::Conf::msg = '';
124
125 # Launch reqInit() if exists
126 if ( $self->can('reqInit') ) {
127 $self->reqInit($req);
128 }
129
130 # Only words are taken in path
131 my $last = 0;
132 my @path = grep {
133 $last = 1 if ( $_ =~ /[^\.\w]/ );
134 ( $last or /^$/ ? 0 : 1 );
135 } split /\//, $req->path();
136 $self->logger->debug( "Start routing " . ( $path[0] // 'default route' ) );
137
138 if ( !@path and $self->defaultRoute ) {
139 @path = ( $self->defaultRoute );
140 }
141 my $head = 0;
142 my $method = $req->method;
143 if ( $method eq 'HEAD' ) {
144 $head = 1;
145 $method = 'GET';
146 }
147 my $res = $self->followPath( $req, $self->routes->{$method}, \@path );
148 if ( $res and $head ) { $res->[2] = [] }
149 return $res ? $res : $self->sendError( $req, 'Bad request', 400 );
150 }
151
152 sub followPath {
153 my ( $self, $req, $routes, $path ) = @_;
154 if ( $path->[0] and defined $routes->{ $path->[0] } ) {
155 my $w = shift @$path;
156 if ( ref( $routes->{$w} ) eq 'CODE' ) {
157 return $routes->{$w}->( $self, $req, @$path );
158 }
159 my $res = $self->followPath( $req, $routes->{$w}, $path );
160 return $res if ($res);
161 unshift @$path, $w;
162 }
163 if ( $routes->{':'} ) {
164 my $v = shift @$path;
165 $req->set_param( $routes->{'#'}, $v );
166 if ( ref( $routes->{':'} ) eq 'CODE' ) {
167 return $routes->{':'}->( $self, $req, @$path );
168 }
169 return $self->followPath( $req, $routes->{':'}, $path );
170 }
171 elsif ( my $sub = $routes->{'*'} ) {
172 return $self->$sub( $req, @$path );
173 }
174 else {
175 return undef;
176 }
177 }
178
179 1;
180 __END__
181
182 =head1 NAME
183
184 =encoding utf8
185
186 Lemonldap::NG::Common::PSGI::Router - Base library for REST APIs of Lemonldap::NG.
187
188 =head1 SYNOPSIS
189
190 package My::PSGI;
191
192 use base Lemonldap::NG::Common::PSGI::Router;
193
194 sub init {
195 my ($self,$args) = @_;
196 # Will be called 1 time during startup
197
198 # Declare REST routes (could be HTML templates or methods)
199 $self->addRoute ( 'index.html', undef, ['GET'] )
200 ->addRoute ( books => { ':book' => 'booksMethod' }, ['GET', 'POST'] )
201 ->addRoute ( properties => { '*' => 'propertiesMethod' }, ['GET', 'POST', 'PUT', 'DELETE']);
202
203 # Default route (ie: PATH_INFO == '/')
204 $self->defaultRoute('index.html');
205
206 # See Lemonldap::NG::Common::PSGI for other options
207
208 # Return a boolean. If false, then error message has to be stored in
209 # $self->error
210 return 1;
211 }
212
213 sub booksMethod {
214 my ( $self, $req, @otherPathInfo ) = @_;
215 my $book = $req->params('book');
216 my $method = $req->method;
217 ...
218 $self->sendJSONresponse(...);
219 }
220
221 sub propertiesMethod {
222 my ( $self, $property, @otherPathInfo ) = @_;
223 my $method = $req->method;
224 ...
225 $self->sendJSONresponse(...);
226 }
227
228 This package could then be called as a CGI, using FastCGI,...
229
230 #!/usr/bin/env perl
231
232 use My::PSGI;
233 use Plack::Handler::FCGI; # or Plack::Handler::CGI
234
235 Plack::Handler::FCGI->new->run( My::PSGI->run() );
236
237 =head1 DESCRIPTION
238
239 This package provides base class for Lemonldap::NG REST API but could be
240 used regardless.
241
242 =head1 METHODS
243
244 See L<Lemonldap::NG::Common::PSGI> for logging methods, content sending,...
245
246 =head2 Initialization methods
247
248 =head3 addRoute ( $word, $dest, $methods )
249
250 Declare a REST route. Arguments:
251
252 =over
253
254 =item $word:
255
256 the first word of /path/info.
257
258 =item $dest:
259
260 string, sub ref or hash ref (see "Route types" below)
261
262 =item $methods:
263
264 array ref containing the methods concerned by this route.
265
266 =back
267
268 =head4 Route types
269
270 As seen in "SYNOPSIS", you can declare routes with variable component. $dest
271 can be:
272
273 =over
274
275 =item a word:
276
277 the name of the method to call
278
279 =item undef:
280
281 $word is used as $dest
282
283 =item a ref to code:
284
285 an anonymous subroutin to call
286
287 =item a hash ref:
288
289 it's a recursive call to `{ $word => $dest }`
290
291 =item an array ref:
292
293 in this case each element of the array will be considered as
294 `{ $element => $element }`. So each element must be a word that makes a
295 correspondence between a path_info word and a subroutine
296
297 =back
298
299 Some special $word:
300
301 =over
302
303 =item ':name':
304
305 the word in path_info will be stored in GET parameters
306
307 =item '*':
308
309 the subroutine will be called with the word of path_info as second argument
310 (after $req)
311
312 =item 'something.html':
313
314 if $word finishes with '.html', and $dest is undef, then sendHtml() will be
315 called with 'something.tpl' as template name.
316
317 =back
318
319 Examples:
320
321 =over
322
323 =item to manage http://.../books/127 with book() where 127 is the book number, use:
324
325 $self->addRoute( books => { ':bookId' => 'book' }, ['GET'] );
326
327 bookId parameter will be stored in $req->params('bookId');
328
329 =item to manage http://.../books/127/pages/5 with page(), use:
330
331 $self->addRoute( books => { ':bookId' => { pages => { ':pageId' => 'page' } } }, ['GET'] );
332
333 =item to manage simultaneously the 2 previous examples
334
335 $self->addRoute( books => { ':bookId' => { pages => { ':pageId' => 'page' } } }, ['GET'] )
336 ->addRoute( books => { ':bookId' => { '*' => 'book' } }, ['GET'] );
337
338 Note that book() will be called for any path_info containing /books/<$bookid>/<$other>
339 except if $other == 'pages'.
340
341 =item to manage /properties/p1, /properties/p2 with p1() and p2(), use:
342
343 $self->addRoute( properties => [ 'p1', 'p2' ] );
344
345 =back
346
347 =head3 defaultRoute($path)
348
349 This method defined which path_info to use if path_info is '/' or empty.
350
351 =head2 Accessors
352
353 See L<Lemonldap::NG::Common::PSGI> for inherited accessors (error, languages,
354 logLevel, staticPrefix, templateDir, links, syslog).
355
356 =head1 SEE ALSO
357
358 L<http://lemonldap-ng.org/>, L<Lemonldap::NG::Portal>, L<Lemonldap::NG::Handler>,
359 L<Plack>, L<PSGI>, L<Lemonldap::NG::Common::PSGI>,
360 L<Lemonldap::NG::Common::PSGI::Request>, L<HTML::Template>,
361
362 =head1 AUTHORS
363
364 =over
365
366 =item LemonLDAP::NG team L<http://lemonldap-ng.org/team>
367
368 =back
369
370 =head1 BUG REPORT
371
372 Use OW2 system to report bug or ask for features:
373 L<https://gitlab.ow2.org/lemonldap-ng/lemonldap-ng/issues>
374
375 =head1 DOWNLOAD
376
377 Lemonldap::NG is available at
378 L<https://lemonldap-ng.org/download>
379
380 =head1 COPYRIGHT AND LICENSE
381
382 See COPYING file for details.
383
384 This library is free software; you can redistribute it and/or modify
385 it under the terms of the GNU General Public License as published by
386 the Free Software Foundation; either version 2, or (at your option)
387 any later version.
388
389 This program is distributed in the hope that it will be useful,
390 but WITHOUT ANY WARRANTY; without even the implied warranty of
391 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
392 GNU General Public License for more details.
393
394 You should have received a copy of the GNU General Public License
395 along with this program. If not, see L<http://www.gnu.org/licenses/>.
396
397 =cut