view Lib/IMPL/Web/Handler/JSONView.pm @ 285:546957c50a36

*IMPL::Web::Handler::TTView Reworked template selection mechanism *IMPL::Web::Application: refactoring -Removed obsolete IMPL::Text modules
author cin
date Mon, 18 Feb 2013 02:55:59 +0400
parents 32aceba4ee6d
children 52aae1b85084
line wrap: on
line source

package IMPL::Web::Handler::JSONView;
use strict;
use JSON;

use IMPL::lang qw(is);
use IMPL::declare {
    require => {
        HttpResponse => 'IMPL::Web::HttpResponse',
        ViewResult => '-IMPL::Web::ViewResult'        
    },
	base => [
		'IMPL::Object' => undef,
		'IMPL::Object::Serializable' => undef,
		'IMPL::Object::Autofill' => '@_'
	]
};

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;
	
	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