comparison 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
comparison
equal deleted inserted replaced
117:0475eb382085 118:79cdd6c86409
1 package IMPL::Web::QueryHandler::JsonTransform;
2 package IMPL::Web::QueryHandler::JsonFormat;
3 use strict;
4 use base qw(IMPL::Web::QueryHandler);
5
6 __PACKAGE__->PassThroughArgs;
7
8 use Error qw(:try);
9 use JSON;
10
11 sub Process {
12 my ($this,$action,$nextHandler) = @_;
13
14 my $transform = new IMPL::Web::QueryHandler::JsonTransform();
15
16 my $result;
17 try {
18 $result = $nextHandler->();
19 } otherwise {
20 my $err = shift;
21 $result = { error => $err };
22 };
23
24 $action->response->contentType('text/javascript');
25 my $hout = $action->response->streamBody;
26 print $hout to_json($result, {pretty => 1} );
27 }
28
29 package IMPL::Web::QueryHandler::JsonTransform;
30
31 use base qw(IMPL::Transform);
32 use IMPL::Class::Property;
33
34 BEGIN {
35 public property cacheClassProps => prop_all;
36 }
37
38 our %CTOR = (
39 'IMPL::Transform' => sub {
40
41 -plain => sub { $_[1]; }, # keep plains as is
42
43 HASH => sub { $_[1]; }, # keep arrays as is
44
45 'IMPL::Object::List' => sub { [$_[1]->as_list()] }, # make a copy
46
47 -default => sub { # convert to hash
48 my ($this,$object) = @_;
49
50 my $propList = $this->cacheClassProps->{ref $object};
51 unless ($propList) {
52 # derived first, then own properties, only public
53 my %props = map { $_->name, $_ } $this->get_meta( 'IMPL::Class::PropertyInfo', sub { $_->Access == IMPL::Class::Member::MOD_PUBLIC } , 1 );
54 $this->cacheClassProps->{ref $object} = $propList = [keys %props];
55
56 }
57
58 return {
59 map {
60 $_,
61 $this->Transform($object->$_())
62 } @$propList
63 };
64 }
65 }
66 );
67
68 sub CTOR {
69 my ($this) = @_;
70
71 $this->cacheClassProps({});
72 }
73
74 1;
75
76 __END__
77
78 =pod
79
80 =cut