Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions M4/practica/api/app/controllers/CiudadController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace App\Controllers;

use Controller;
use Response;
use App\Models\Ciudad;

class CiudadController extends Controller
{
public function get()
{
return Response::json(Ciudad::all());
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fijate lo parecido que es todo este controller al de Presidentes... incluso el de clientes también tendría este método (lo que pasa es que le hicimos una funcionalidad rara, pero en un caso normal también tendría un get así como este)...

Sale hacer un controller base? 😉

}
}
57 changes: 44 additions & 13 deletions M4/practica/api/app/controllers/ClienteController.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,65 @@

namespace App\Controllers;

use App\Models\Cliente;
use Controller;
use Input;
use Response;
use App\Models\Cliente;
use Input;
use DateTime;

class ClienteController extends Controller
{
public function get()
public function get($id = false, $cantidad = 1)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No me gusta esto. El limit no debería ser un parámetro de la URL. No es REST eso

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tenes razon, cantidad no es un atributo del cliente.

{
$clientes = Cliente::where('id', '>=', Input::get('desde', 1))
->whereRaw('id % 2 = ' . (Input::get('filtro') == 'par' ? 0 : 1))
->limit(Input::get('cantidad', 5))
->get();
$cantidad = $cantidad > 5 ? 5 : $cantidad;

if ($id === false) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dado que hacen dos cosas COMPLETAMENTE distintas según "si llegó ID o no", no está bien que sean una misma función. Deberían ser dos funciones completamente separadas

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Y ahí en ese caso tendrías el Cliente::all() y podrías heredar esa función de BaseController que tenés q hacer 😄

return Response::json(
Cliente::all()
);

return Response::json($clientes);
} else {
$clientes = Cliente
::where('id', '>=', $id)
->whereRaw('id % 2 = ?', array($id & 1))
->limit($cantidad)
->get();
sleep($id & 1 ? 3 : 0);
return Response::json($cantidad == 1 ? array($clientes) : $clientes);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

En vez de $cantidad podés hacer min($cantidad, 5)

}
}

public function delete($id)
{
/** @var $cliente Cliente */
$cliente = Cliente::findOrFail($id);
$cliente->delete();

return Response::json(array('id' => $cliente->id));
if (!is_null($cliente = Cliente::find($id))) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Debería alcanzar con

if (!($cliente = Cliente::find($id))) {

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

En este caso si, porque supongo que Model devuelve null y no alguna otra cosa que evalua a null. Lo saque de Model el is_null, pero recorda que !$var es lo mismo que $var != null pero is_null es lo mismo que $var !== null

$cliente->delete();
}
sleep(2);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Está bien que dejes este sleep para hacer pruebas del frontend, pero cuando se sube a github hay que sacarlo ☝️

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Si entiendo el concepto de entornos de laravel, creo que tendria que duplicar los archivos que escribo en app/config, en app/config/local (o dev, o lo q sea), y si entiendo bien, lo que me pedis es que configure git para que ignore todo lo que este dentro de app/config/local, no?

return Response::json(array('id' => $id), is_null($cliente) ? 404 : 200);
}

public function post()
{
return Response::json(Cliente::create(Input::all()));
$datos = Input::all();
if (!$this->validar_post($datos)) {
return Response::json(array(), 400);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Acá no está bien que devolvamos un array vacío. Pensá que el tipo del frontend tiene que saber qué es lo que falló.
Con este mensaje estamos diciendo "ALGO FALLÓ" jajajaja

Lo que se usa es mandar un array assco con el nombre del campo que falló, y el motivo. Laravel (Ardent) lo maneja solito eso, con las $rules, y cuando se quiere agregar alguna en particular se intenta replicar ese funcionamiento, así al frontend le enseñamos a entender esas respuestas y listo.

Desde angular lo que se hace después es "interceptar" el $http, y fijarnos el status code. Cuando llegó un 400, buscamos el mensaje de error en el response y lo lanzamos en un alert (o algo más lindo)

}
$datos['fecha_creacion'] = (new DateTime('now'))->format('l, F d, Y H:i A');
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hay una clase para el manejo de fechas que se llama CARBON. Creo que viene con Laravel, chequeala después.

$cliente = Cliente::create($datos);
return Response::json($cliente);
}

private function validar_post($datos)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

camelCase

{
if (!count($datos)) {
return false;
}
foreach ($datos as $key => $value) {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Para validar que todo esto no sea empty, podés instanciar un Validator. Es una clase que viene en Laravel, a la cual le indicás un set de reglas ($rules) y le das un array y le decís tipo "Tomá, Validator. Validame este array y fijate que cumplan con estas reglas".

Y después le podés preguntar si es valido (podés hacer tipo return $validator->passes();)

if (empty($value)) {
return false;
}
}
return true;
}
}
11 changes: 4 additions & 7 deletions M4/practica/api/app/controllers/PresidenteController.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,8 @@

class PresidenteController extends Controller
{
public function get()
{
return Response::json(
Presidente::all()
);
}

public function get()
{
return Response::json(Presidente::all());
}
}
25 changes: 25 additions & 0 deletions M4/practica/api/app/models/Ciudad.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace App\Models;

use Eloquent;

class Ciudad extends Eloquent
{
protected $table = 'ciudades';
public $timestamps = false;

protected $hidden = array(
// 'id',
'pais_id'
);

protected $with = array(
'pais'
);

public function pais()
{
return $this->belongsTo('App\\Models\\Pais');
}
}
14 changes: 10 additions & 4 deletions M4/practica/api/app/models/Cliente.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,30 +7,36 @@
class Cliente extends Eloquent
{
protected $table = 'clientes';

public $timestamps = false;

protected $fillable = array(
'razon_social',
'logo',
'direccion_calle',
'direccion_altura',
'direccion_ciudad',
'pais_id',
'ciudad_id',
'activo',
'pasivo',
'presidente_id'
);

protected $hidden = array(
'ciudad_id',
'presidente_id'
);

protected $with = array(
'ciudad',
'presidente'
);

public function presidente() {
public function ciudad()
{
return $this->belongsTo('App\\Models\\Ciudad');
}

public function presidente()
{
return $this->belongsTo('App\\Models\\Presidente');
}
}
5 changes: 4 additions & 1 deletion M4/practica/api/app/models/Pais.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
class Pais extends Eloquent
{
protected $table = 'paises';

public $timestamps = false;

protected $hidden = array(
'id'
);
}
5 changes: 4 additions & 1 deletion M4/practica/api/app/models/Presidente.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
class Presidente extends Eloquent
{
protected $table = 'presidentes';

public $timestamps = false;

protected $hidden = array(
// 'id'
);
}
10 changes: 8 additions & 2 deletions M4/practica/api/app/routes.php
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
<?php

Route::pattern('id', '[0-9]+');
Route::pattern('cantidad', '[0-9]+');

// Clientes
Route::get('cliente/{id?}/{cantidad?}', 'App\\Controllers\\ClienteController@get');
Route::post('cliente', 'App\\Controllers\\ClienteController@post');
Route::get('cliente', 'App\\Controllers\\ClienteController@get');
Route::put('cliente/{id}', 'App\\Controllers\\ClienteController@put');
Route::delete('cliente/{id}', 'App\\Controllers\\ClienteController@delete');
Route::put('cliente/{id}', 'App\\Controllers\\ClienteController@put');

// Presidentes
Route::get('presidente', 'App\\Controllers\\PresidenteController@get');

// Ciudades
Route::get('ciudad', 'App\\Controllers\\CiudadController@get');
4 changes: 3 additions & 1 deletion M4/practica/bower.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
],
"dependencies": {
"jquery": "~2.1.4",
"bootstrap": "~3.3.5"
"bootstrap": "~3.3.5",
"angular": "~1.4.7",
"angular-bootstrap": "~0.14.3"
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Qué pasó acá con el indent? jajajaja esto no lo aprueba el SNIFFER!

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No ibas a agregar angular-ui?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agregue angular-bootstrap desde notepad++ y esta configurado para usar tabs en vez de espacios...
Al final, si bien angular-ui y las 20 variantes son todas del mismo repo (si no me equivoco), era angular-bootstrap la que tenia el tooltip que yo necesitaba de bootstrap.js y que no funcionaba con angular.

}
}
Loading