-
Notifications
You must be signed in to change notification settings - Fork 0
/
treejo.psgi
51 lines (43 loc) · 1.35 KB
/
treejo.psgi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/env perl
use 5.018;
use warnings;
use Plack::App::Directory;
use Plack::Builder;
use Plack::Request;
use FindBin qw/ $Bin /;
sub get_node_data {
my ( $id, $has_children )= @_;
return '{'
. '"title":"title-' . $id . '", '
. '"body":"body-' . $id . '"'
. ( rand(1) > 0.6 ? ',"classes":["node-danger"]' : '' )
. ( $has_children ? ',"url":"/api?node_id=' . $id . '"' : '' )
. '}';
}
my $api_app = sub {
my $env = shift;
my $req = Plack::Request->new($env);
my $node_id = $req->parameters->{node_id};
my $num_nodes = 2 + int( rand(4) ); # [2-5]
my @nodes;
my $depth = split( /\./, $node_id ); # 1.1.2 => 3, 1.3.4.1 => 4, ...
for my $i ( 1 .. $num_nodes ) {
# stop delivery of nodes if depth > 5
my $has_children = $depth <= 5
? rand(1) > 0.5 ? 1 : 0
: 0;
push(
@nodes,
get_node_data( "$node_id.$i", $has_children )
);
}
my $json = '{'
. '"name":"node-' . $node_id . '",'
. '"child_nodes":[' . join( ',', @nodes ) . ']'
. '}';
return [ 200, [ 'Content-Type' => 'application/json' ], [$json] ];
};
builder {
mount '/' => Plack::App::Directory->new({ root => $Bin })->to_app;
mount '/api' => $api_app;
}