Update the MANIFEST for test changes.
[catagits/Catalyst-Engine-STOMP.git] / lib / Catalyst / Controller / MessageDriven.pm
CommitLineData
0a663589 1package Catalyst::Controller::MessageDriven;
2use Moose;
bf8937b7 3use YAML::XS qw/ LoadFile Dump /;
0a663589 4
5BEGIN { extends 'Catalyst::Controller' }
6
d78bb739 7=head1 NAME
8
9Catalyst::Controller::MessageDriven
10
11=head1 SYNOPSIS
12
13 package MyApp::Controller::Queue;
14 use Moose;
15 BEGIN { extends 'Catalyst::Controller::MessageDriven' }
16
17 sub some_action : Local {
bf8937b7 18 my ($self, $c, $message) = @_;
19
20 # Handle message
21
d78bb739 22 # Reply with a minimal response message
23 my $response = { type => 'testaction_response' };
24 $c->stash->{response} = $response;
25 }
26
27=head1 DESCRIPTION
28
29A Catalyst controller base class for use with Catalyst::Engine::Stomp,
30which handles YAML-serialized messages. A top-level "type" key in the
31YAML determines the action dispatched to.
32
33=cut
34
bf8937b7 35sub begin : Private {
36 my ($self, $c) = @_;
37
38 # Deserialize the request message
39
40 my $message;
41 eval {
42 my $body = $c->request->body;
43 $message = LoadFile( "$body" );
44 };
45 if ($@) {
46 # can't reply - reply_to is embedded in the message
47 $c->error("exception in deserialize: $@");
48 }
49 else {
50 $c->stash->{request} = $message;
51 }
52}
0a663589 53
bf8937b7 54sub end : Private {
0a663589 55 my ($self, $c) = @_;
56
57 # Engine will send our reply based on the value of this header.
bf8937b7 58 $c->response->headers->header( 'X-Reply-Address' => $c->stash->{request}->{reply_to} );
0a663589 59
60 # Custom error handler - steal errors from catalyst and dump them into
61 # the stash, to get them serialized out as the reply.
62 if (scalar @{$c->error}) {
63 my $error = join "\n", @{$c->error};
64 $c->stash->{response} = { status => 'ERROR', error => $error };
65 $c->error(0); # clear errors, so our response isn't clobbered
66 }
bf8937b7 67
68 # Serialize the response
69 my $output;
70 eval {
71 $output = Dump( $c->stash->{response} );
72 };
73 if ($@) {
74 my $error = "exception in serialize: $@";
75 $c->error($error);
76 $c->stash->{response} = { status => 'ERROR', error => $error };
77 $output = Dump( $c->stash->{response} );
78 }
79
80 $c->response->output( $output );
0a663589 81}
82
83sub default : Private {
84 my ($self, $c) = @_;
bf8937b7 85
0a663589 86 # Forward the request to the appropriate action, based on the
87 # message type.
bf8937b7 88 my $action = $c->stash->{request}->{type};
89 $c->forward($action, [$c->stash->{request}]);
0a663589 90}
91
92__PACKAGE__->meta->make_immutable;
93
941;