Mercurial > pub > Impl
diff 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 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/lib/IMPL/Web/Handler/JSONView.pm Fri Sep 04 19:40:23 2015 +0300 @@ -0,0 +1,70 @@ +package IMPL::Web::Handler::JSONView; +use strict; +use JSON; + +use IMPL::lang qw(is); +use IMPL::Const qw(:prop); +use IMPL::declare { + require => { + HttpResponse => 'IMPL::Web::HttpResponse', + ViewResult => '-IMPL::Web::ViewResult', + Loader => 'IMPL::Code::Loader' + }, + base => [ + 'IMPL::Object' => undef, + 'IMPL::Object::Serializable' => undef, + 'IMPL::Object::Autofill' => '@_' + ], + props => [ + transform => PROP_RW + ] +}; + +sub contentType { + 'application/json' +} + +sub Invoke { + my ($this,$action,$next) = @_; + + my $result = $next ? $next->($action) : undef; + + + my $model = ( ref $result and is($result,ViewResult) ) + ? $result->model + : $result; + + $model = [$model] unless ref $model; + + if (my $factory = $this->transform) { + Loader->safe->Require($factory) unless ref $factory; + my $t = $this->transform->new(); + $model = $t->Transform($model); + } + + my %params = ( + type => $this->contentType, + charset => 'utf-8', + body => JSON->new->utf8->pretty->encode($model) + ); + + if(is($result,ViewResult)) { + $params{status} = $result->status if $result->status; + $params{headers} = $result->headers if $result->headers; + $params{cookies} = $result->cookies if $result->cookies; + } + + return HttpResponse->new( + %params + ); +} + +1; + +__END__ + +=pod + +=head1 + +=cut \ No newline at end of file