mirror of
https://git.imnavajas.es/jjimenez/safekat.git
synced 2025-07-25 22:52:08 +00:00
Implementado filtro CORS y ejemplo de resources para la API
This commit is contained in:
103
ci4/app/Controllers/API/ItemsController.php
Normal file
103
ci4/app/Controllers/API/ItemsController.php
Normal file
@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers\API;
|
||||
|
||||
use CodeIgniter\RESTful\ResourceController;
|
||||
use CodeIgniter\API\ResponseTrait;
|
||||
use App\Models\API\ItemModel;
|
||||
|
||||
class ItemsController extends ResourceController
|
||||
{
|
||||
|
||||
use ResponseTrait;
|
||||
|
||||
public function index()
|
||||
{
|
||||
$model = new ItemModel();
|
||||
$data = $model->findAll();
|
||||
return $this->respond($data);
|
||||
}
|
||||
|
||||
public function show($id = null)
|
||||
{
|
||||
$model = new ItemModel();
|
||||
$data = $model->find(['id' => $id]);
|
||||
if (!$data)
|
||||
return $this->failNotFound('No Data Found');
|
||||
return $this->respond($data[0]);
|
||||
}
|
||||
|
||||
public function create()
|
||||
{
|
||||
helper(['form']);
|
||||
$rules = [
|
||||
'title' => 'required',
|
||||
'price' => 'required'
|
||||
];
|
||||
$data = [
|
||||
'title' => $this->request->getVar('title'),
|
||||
'price' => $this->request->getVar('price')
|
||||
];
|
||||
|
||||
if (!$this->validate($rules))
|
||||
return $this->fail($this->validator->getErrors());
|
||||
$model = new ItemModel();
|
||||
$model->save($data);
|
||||
$response = [
|
||||
'status' => 201,
|
||||
'error' => null,
|
||||
'messages' => [
|
||||
'success' => 'Data Inserted'
|
||||
]
|
||||
];
|
||||
return $this->respondCreated($response);
|
||||
}
|
||||
|
||||
public function update($id = null)
|
||||
{
|
||||
helper(['form']);
|
||||
$rules = [
|
||||
'title' => 'required',
|
||||
'price' => 'required'
|
||||
];
|
||||
$data = [
|
||||
'title' => $this->request->getVar('title'),
|
||||
'price' => $this->request->getVar('price')
|
||||
];
|
||||
|
||||
if (!$this->validate($rules))
|
||||
return $this->fail($this->validator->getErrors());
|
||||
$model = new ItemModel();
|
||||
$find = $model->find(['id' => $id]);
|
||||
if (!$find)
|
||||
return $this->failNotFound('No Data Found');
|
||||
$model->update($id, $data);
|
||||
|
||||
$response = [
|
||||
'status' => 200,
|
||||
'error' => null,
|
||||
'messages' => [
|
||||
'success' => 'Data updated'
|
||||
]
|
||||
];
|
||||
return $this->respond($response);
|
||||
}
|
||||
|
||||
public function delete($id = null)
|
||||
{
|
||||
$model = new ItemModel();
|
||||
$find = $model->find(['id' => $id]);
|
||||
if (!$find)
|
||||
return $this->failNotFound('No Data Found');
|
||||
$model->delete($id);
|
||||
|
||||
$response = [
|
||||
'status' => 200,
|
||||
'error' => null,
|
||||
'messages' => [
|
||||
'success' => 'Data deleted'
|
||||
]
|
||||
];
|
||||
return $this->respond($response);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user