comparison lib/IMPL/Web/Handler/JSONView.pm @ 407:c6e90e02dd17 ref20150831

renamed Lib->lib
author cin
date Fri, 04 Sep 2015 19:40:23 +0300
parents
children
comparison
equal deleted inserted replaced
406:f23fcb19d3c1 407:c6e90e02dd17
1 package IMPL::Web::Handler::JSONView;
2 use strict;
3 use JSON;
4
5 use IMPL::lang qw(is);
6 use IMPL::Const qw(:prop);
7 use IMPL::declare {
8 require => {
9 HttpResponse => 'IMPL::Web::HttpResponse',
10 ViewResult => '-IMPL::Web::ViewResult',
11 Loader => 'IMPL::Code::Loader'
12 },
13 base => [
14 'IMPL::Object' => undef,
15 'IMPL::Object::Serializable' => undef,
16 'IMPL::Object::Autofill' => '@_'
17 ],
18 props => [
19 transform => PROP_RW
20 ]
21 };
22
23 sub contentType {
24 'application/json'
25 }
26
27 sub Invoke {
28 my ($this,$action,$next) = @_;
29
30 my $result = $next ? $next->($action) : undef;
31
32
33 my $model = ( ref $result and is($result,ViewResult) )
34 ? $result->model
35 : $result;
36
37 $model = [$model] unless ref $model;
38
39 if (my $factory = $this->transform) {
40 Loader->safe->Require($factory) unless ref $factory;
41 my $t = $this->transform->new();
42 $model = $t->Transform($model);
43 }
44
45 my %params = (
46 type => $this->contentType,
47 charset => 'utf-8',
48 body => JSON->new->utf8->pretty->encode($model)
49 );
50
51 if(is($result,ViewResult)) {
52 $params{status} = $result->status if $result->status;
53 $params{headers} = $result->headers if $result->headers;
54 $params{cookies} = $result->cookies if $result->cookies;
55 }
56
57 return HttpResponse->new(
58 %params
59 );
60 }
61
62 1;
63
64 __END__
65
66 =pod
67
68 =head1
69
70 =cut