Skip to content

Instantly share code, notes, and snippets.

@phillipadsmith
Last active December 21, 2015 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phillipadsmith/edd40a94a98c0cd0fc69 to your computer and use it in GitHub Desktop.
Save phillipadsmith/edd40a94a98c0cd0fc69 to your computer and use it in GitHub Desktop.
# http://localhost:3000/items/3.json?cb=mycallback <= WORKS!
# http://localhost:3000/items/3.json <= breaks with this error:
# Can't locate object method "render_json" via package "Mojolicious::Controller" at /Users/phillipadsmith/perl5/perlbrew/perls/perl-5.16.1/lib/site_perl/5.16.1/Mojolicious/Plugin/JSONP.pm line 20.
#!/usr/bin/env perl
use strict;
use warnings;
use Mojolicious::Lite;
use Modern::Perl '2013';
use Data::Dumper;
use Try::Tiny;
use Wires::Schema;
plugin JSONP => callback => 'cb';
my $config = plugin 'JSONConfig';
helper schema => sub {
my $schema = Wires::Schema->connect( $config->{'pg_dsn'},
$config->{'pg_user'}, $config->{'pg_pass'}, );
return $schema;
};
# Get items with optional limit or page
get '/items/:limit/:page' => { limit => '10', page => '1' } => sub {
my $self = shift;
my $limit = $self->stash( 'limit' );
my $page = $self->stash( 'page' );
my @items = $self->schema->resultset( 'Item' )->search(
undef,
{ page => $page, # page to return (defaults to 1)
rows => $limit, # number of results per page
order_by => { -desc => 'pubdate' },
},
);
my @results;
for my $item ( @items ) {
my $doc = {
title => $item->title,
description => $item->description,
pubdate => $item->pubdate,
};
push @results, $doc;
}
$self->respond_to(
json => sub {
$self->render_jsonp( { result => \@results } ), status => 200;
},
any => { text => '', status => 204 }
);
};
app->secret( $config->{'app_secret'} );
app->start;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment