Created
September 15, 2013 22:30
-
-
Save blabos-zz/6574865 to your computer and use it in GitHub Desktop.
user insertion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use utf8; | |
use strict; | |
use warnings; | |
package App::Schema::ResultSet::User; | |
use Moose; | |
use namespace::autoclean; | |
use Try::Catch; | |
use Email::Valid; | |
extends 'DBIx::Class::ResultSet'; | |
sub new_user { | |
my ( $self, $fields ) = @_; | |
my $txn = sub { | |
my $errors; | |
## not null | |
foreach my $field ( keys %{$fields} ) { | |
push @{$errors}, 'empty_' . $field | |
unless $fields->{$field}; | |
} | |
## unique | |
foreach my $field (qw{ username email }) { | |
push @{$errors}, 'already_' . $field | |
if $self->find( { $field => $fields->{$field} } ); | |
} | |
## invalid email | |
push @{$errors}, 'invalid_email' | |
unless Email::Valid->address( $fields->{email} ); | |
return $errors | |
if @{$errors} > 0; | |
## Create | |
return $self->find_or_create($fields); | |
}; | |
try { | |
$result = $self->result_source->schema->txn_do($txn); | |
} | |
catch { | |
$result = $_; | |
}; | |
return $result; | |
} | |
package App::Controller::User; | |
sub new_user : Chained('/') : PathPart('user/new') : Args(0) { | |
my ( $self, $c ) = @_; | |
my $fields = { | |
full_name => $c->req->params->{full_name} || '', | |
username => $c->req->params->{username} || '', | |
email => $c->req->params->{email} || '', | |
password => $c->req->params->{password} || '', | |
}; | |
my $result = $c->model->resultset('User')->new_user($fields); | |
if ( $result->isa('App::Model::User') ) { | |
$c->stash->{message} = 'add_ok'; | |
} | |
else { | |
$c->stash->{errors} = $result; | |
$c->stash->{user} = $fields; | |
} | |
return; | |
} | |
1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment