1 package Catalyst::Controller::MessageDriven;
4 use Moose::Util::TypeConstraints;
5 use MooseX::Types::Moose qw/Str/;
6 use namespace::autoclean;
8 BEGIN { extends 'Catalyst::Controller' }
12 Catalyst::Controller::MessageDriven
16 package MyApp::Controller::Queue;
18 BEGIN { extends 'Catalyst::Controller::MessageDriven' }
20 sub some_action : Local {
21 my ($self, $c, $message) = @_;
25 # Reply with a minimal response message
26 my $response = { type => 'testaction_response' };
27 $c->stash->{response} = $response;
32 A Catalyst controller base class for use with Catalyst::Engine::Stomp,
33 which handles YAML-serialized messages. A top-level "type" key in the
34 YAML determines the action dispatched to.
40 Deserializes the request into C<< $c->stash->{request} >>
44 Dispatches to method named by the key C<< $c->stash->{request}->{type} >>
48 Serializes the response from C<< $c->stash->{response} >>
52 class_type 'Data::Serializer';
53 my $serializer_t = subtype 'Data::Serializer';
54 coerce $serializer_t, from 'Str',
55 via { Data::Serializer->new( serializer => $_ ) };
58 isa => $serializer_t, is => 'ro', required => 1,
59 default => 'YAML', coerce => 1,
65 # Deserialize the request message
67 my $s = $self->serializer;
69 my $body = $c->request->body;
70 open my $IN, "$body" or die "can't open temp file $body";
71 $message = $s->raw_deserialize(do { local $/; <$IN> });
74 # can't reply - reply_to is embedded in the message
75 $c->error("exception in deserialize: $@");
78 $c->stash->{request} = $message;
85 # Engine will send our reply based on the value of this header.
86 $c->response->headers->header( 'X-Reply-Address' => $c->stash->{request}->{reply_to} );
92 my $s = $self->serializer;
94 # Custom error handler - steal errors from catalyst and dump them into
95 # the stash, to get them serialized out as the reply.
96 if (scalar @{$c->error}) {
97 $c->log->error($_) for @{$c->error}; # Log errors in Catalyst
98 my $error = join "\n", @{$c->error};
99 $c->stash->{response} = { status => 'ERROR', error => $error };
100 $output = $s->serialize( $c->stash->{response} );
102 $c->response->status(400);
105 # Serialize the response
107 $output = $s->raw_serialize( $c->stash->{response} );
110 my $error = "exception in serialize: $@";
111 $c->stash->{response} = { status => 'ERROR', error => $error };
112 $output = $s->serialize( $c->stash->{response} );
113 $c->response->status(400);
116 $c->response->output( $output );
119 sub default : Private {
122 # Forward the request to the appropriate action, based on the
124 my $action = $c->stash->{request}->{type};
125 if (defined $action) {
126 $c->forward($action, [$c->stash->{request}]);
129 $c->error('no message type specified');
133 __PACKAGE__->meta->make_immutable;