Your problem (if I'm reading your code right) is that you don't have
anything to catch when the query has exhausted itself. Instead it looks
like you're immediately calling write_chunk($final_json_stuff) after the
first callback returns, which then closes the JSON object being
constructed, and when the other rows get sent, the most they'll do is
trigger a syntax error at the far end (because they'll be outside of the }
that you sent in $final_json_stuff) and if the far end is sufficiently
badly coded, it'll just snarf enough of the stream to see a complete JSON
object and ignore what follows, and then rows 2-n get silently dropped on
the floor.
Meaning the if in your write_results needs a else (i.e., $query->hash
returns false signalling that there are no more rows), and *that* is where
you want to write your } or whatever it is you're doing to close out the
JSON thingie.
However, I also agree that this stuff really shouldn't be in the model. If
we're really doing MVC-separation right, then the question of generating
JSON is really the job of the *Viewer*, what the controller invokes after
getting the result from the model....
At which point your problem is a model that returns partial results with a
thunk to either get more or indicate we're done -- whether you want to just
pass the Mojo::Pg::Results object around or have something more abstract
wrapping it is up to you -- but, unless I'm missing something, Mojo doesn't
seem to have a notion of "partial template" that can deal with these things
(I'm not even sure what it would look like)...
... so you have to fake it in the controller, which I believe will go
something like
# in the model
sub get_data {
...
return $pg->db->query('SELECT whatever...');
}
# in the controller
$qresult = $model->get_data(...);
$self->write_chunk('{ ..., "rows": [');
my $cb;
my $comma='';
$cb = sub {
my $row = eval { $qresult->hash; };
if($@) {
$controller->finish('], "status" : "error", "msg": '.to_json($@).'}');
}
elsif ($row) {
$controller->write_chunk($comma . to_json($row), $cb);
$comma = ',';
}
else {
$controller->finish('], "status" : "ok" }');
}
}
$cb->();
$self->render_later; # not sure if this is necessary
# DO NOTHING FURTHER HERE
--
You received this message because you are subscribed to the Google Groups
"Mojolicious" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/mojolicious.
For more options, visit https://groups.google.com/d/optout.