Skip to content

Commit

Permalink
Merge pull request #2 from eudiegoborgs/dev
Browse files Browse the repository at this point in the history
Adiciona endpoints
  • Loading branch information
wilcorrea committed Aug 18, 2023
2 parents 78e6234 + 322d671 commit 6c9e3fa
Show file tree
Hide file tree
Showing 11 changed files with 439 additions and 25 deletions.
14 changes: 14 additions & 0 deletions app/Consumer/PersonConsumer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

declare(strict_types=1);

namespace App\Consumer;

use Hyperf\AsyncQueue\Process\ConsumerProcess;
use Hyperf\Process\Annotation\Process;

#[Process(name: "async-queue")]
class PersonConsumer extends ConsumerProcess
{

}
61 changes: 54 additions & 7 deletions app/Controller/PersonController.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,33 +12,80 @@

namespace App\Controller;

use App\Job\PersonJob;
use App\Model\Person;
use App\Request\PersonRequest;
use Hyperf\AsyncQueue\Driver\DriverFactory;
use Hyperf\AsyncQueue\Driver\DriverInterface;
use Hyperf\Database\Model\Builder;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Redis\Redis;
use Psr\Http\Message\ResponseInterface as MessageResponseInterface;

final class PersonController
{
private DriverInterface $driver;

public function __construct(
private Redis $redis,
DriverFactory $driverFactory
) {
$this->driver = $driverFactory->get('default');
}

/**
* @throws \Throwable
*/
public function create(PersonRequest $request, ResponseInterface $response): MessageResponseInterface
{
$person = $request->toPerson();
$person->saveOrFail();

return $response->json($person)->withStatus(201);

if ($this->redis->get($person['nick'])) {
return $response->json(['message' => 'Esse apelido já existe'])->withStatus(422);
}

$this->driver->push(new PersonJob($person));

This comment has been minimized.

Copy link
@medeirosinacio

medeirosinacio Aug 18, 2023

Era exatamente isso, primeiro cache e depois a aplicação se vira para salvar no DB.


//

$this->redis->set($person['nick'], '.');
$this->redis->set($person['id'], json_encode($person));

return $response->json($person)->withStatus(201)->withHeader('Location', "/pessoas/{$person['id']}");
}

public function show(RequestInterface $request, ResponseInterface $response): MessageResponseInterface
public function show(RequestInterface $request, ResponseInterface $response, string $id): MessageResponseInterface
{
return $response->raw('Hello Hyperf!');
$cached = $this->redis->get($id);
if ($cached) {

$person = json_decode($cached);

return $response->json($person);
}
$response->raw('Not found')->withStatus(404);
}

public function search(RequestInterface $request, ResponseInterface $response): MessageResponseInterface
{
return $response->raw('Hello Hyperf!');
$term = $request->getQueryParams()['t'] ?? null;
if ($term) {
$list = Person::where(function (Builder $query) use ($term) {
$query->whereRaw("lower(name) like lower(\"%{$term}%\")")
->orWhereRaw("lower(nick) like lower(\"%{$term}%\")")
->orWhereRaw("lower(stack) like lower(\"%{$term}%\")");
})->limit(50)->get();

return $response->json($list);
}

return $response->json(['message' => 'Precisa de um termo na busca'])->withStatus(400);
}

public function count(RequestInterface $request, ResponseInterface $response): MessageResponseInterface
{
return $response->raw('Hello Hyperf!');
$count = Person::count();
return $response->json(['count' => $count]);
}
}
24 changes: 24 additions & 0 deletions app/Job/PersonJob.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

declare(strict_types=1);

namespace App\Job;

use Hyperf\AsyncQueue\Job;
use Hyperf\DbConnection\Db;

class PersonJob extends Job
{
public $params;

public function __construct($params)
{
// It's best to use normal data here. Don't pass the objects that carry IO, such as PDO objects.
$this->params = $params;
}

public function handle()
{
Db::table('person')->insert($this->params);
}
}
5 changes: 4 additions & 1 deletion app/Model/Person.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@ class Person extends Model
/**
* The attributes that should be cast to native types.
*/
protected array $casts = [];
protected array $casts = [
'id' => 'string',
'stack' => 'array'
];

protected array $attributes = [
'stack' => '[]',
Expand Down
9 changes: 5 additions & 4 deletions app/Request/PersonRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use App\Model\Person;
use Hyperf\Codec\Json;
use Hyperf\Validation\Request\FormRequest;
use Ramsey\Uuid\Uuid;

final class PersonRequest extends FormRequest
{
Expand All @@ -40,16 +41,16 @@ public function rules(): array
];
}

public function toPerson(): Person
public function toPerson(): array
{
$data = $this->validated();

return Person::create([
'id' => random_bytes(16),
return [
'id' => Uuid::uuid4()->toString(),
'nick' => $data['apelido'],
'name' => $data['nome'],
'birth' => $data['nascimento'],
'stack' => Json::encode($data['stack'] ?? null),
]);
];
}
}
4 changes: 3 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"license": "MIT",
"require": {
"php": ">=8.0",
"hyperf/async-queue": "^3.0",
"hyperf/cache": "^3.0",
"hyperf/command": "^3.0",
"hyperf/config": "^3.0",
Expand All @@ -26,7 +27,8 @@
"hyperf/process": "^3.0",
"hyperf/redis": "^3.0",
"hyperf/translation": "^3.0",
"hyperf/validation": "^3.0"
"hyperf/validation": "^3.0",
"ramsey/uuid": "^4.7"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^3.0",
Expand Down
Loading

0 comments on commit 6c9e3fa

Please sign in to comment.