changeset 118:79cdd6c86409

JSON support (experimental)
author wizard
date Mon, 07 Jun 2010 08:21:26 +0400
parents 0475eb382085
children 41e9d9ea3db5
files Lib/IMPL/Web/QueryHandler/JsonFormat.pm
diffstat 1 files changed, 80 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Lib/IMPL/Web/QueryHandler/JsonFormat.pm	Mon Jun 07 08:21:26 2010 +0400
@@ -0,0 +1,80 @@
+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
\ No newline at end of file