view Lib/IMPL/Web/QueryHandler/JsonFormat.pm @ 118:79cdd6c86409

JSON support (experimental)
author wizard
date Mon, 07 Jun 2010 08:21:26 +0400
parents
children 41e9d9ea3db5
line wrap: on
line source

package IMPL::Web::QueryHandler::JsonTransform;
package IMPL::Web::QueryHandler::JsonFormat;
use strict;
use base qw(IMPL::Web::QueryHandler);

__PACKAGE__->PassThroughArgs;

use Error qw(:try);
use JSON;

sub Process {
	my ($this,$action,$nextHandler) = @_;
	
	my $transform = new IMPL::Web::QueryHandler::JsonTransform();
	
	my $result;
	try {
		$result = $nextHandler->();
	} otherwise {
		my $err = shift;
		$result = { error => $err };
	};
	
	$action->response->contentType('text/javascript');
	my $hout = $action->response->streamBody;
	print $hout to_json($result, {pretty => 1} );
}

package IMPL::Web::QueryHandler::JsonTransform;

use base qw(IMPL::Transform);
use IMPL::Class::Property;

BEGIN {
	public property cacheClassProps => prop_all;
}

our %CTOR = (
	'IMPL::Transform' => sub {
	
		-plain => sub { $_[1]; }, # keep plains as is
	
		HASH => sub { $_[1]; }, # keep arrays as is
	
		'IMPL::Object::List' => sub { [$_[1]->as_list()] }, # make a copy
	
		-default => sub { # convert to hash
			my ($this,$object) = @_;
		
			my $propList = $this->cacheClassProps->{ref $object};
			unless ($propList) {
				# derived first, then own properties, only public
				my %props = map { $_->name, $_ } $this->get_meta( 'IMPL::Class::PropertyInfo', sub { $_->Access == IMPL::Class::Member::MOD_PUBLIC } , 1 );
				$this->cacheClassProps->{ref $object} = $propList = [keys %props];
				
			}
			
			return {
				map {
					$_,
					$this->Transform($object->$_())
				} @$propList
			};
		}
	}
);

sub CTOR {
	my ($this) = @_;
	
	$this->cacheClassProps({});
}

1;

__END__

=pod

=cut