Skip to content

Commit

Permalink
Corrigido testes e refaturado (#5)
Browse files Browse the repository at this point in the history
* chore: Start application

* chore(docs): Styling

* fix tests and refactor

* chore: Remove unused file

Esse arquivo da participação ficaria só na `main`.

---------

Co-authored-by: leocavalcante <leonardo.cavalcante@picpay.com>
Co-authored-by: Leo Cavalcante <lc@leocavalcante.com>
Co-authored-by: William Correa <william.correa@picpay.com>
  • Loading branch information
4 people committed Aug 19, 2023
1 parent b0b992d commit 8abcb5f
Show file tree
Hide file tree
Showing 16 changed files with 120 additions and 73 deletions.
2 changes: 1 addition & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ DB_CHARSET=utf8mb4
DB_COLLATION=utf8mb4_unicode_ci
DB_PREFIX=

REDIS_HOST=localhost
REDIS_HOST=cache
REDIS_AUTH=(null)
REDIS_PORT=6379
REDIS_DB=0
10 changes: 9 additions & 1 deletion app/Consumer/PersonConsumer.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@

declare(strict_types=1);

/**
* This file is part of OpenCodeCo.
*
* @link https://github.com/opencodeco/rinha-de-backend-2023-q3
* @document https://github.com/opencodeco/rinha-de-backend-2023-q3/wiki
* @contact https://github.com/opencodeco/rinha-de-backend-2023-q3/discussions
* @license https://github.com/opencodeco/rinha-de-backend-2023-q3/blob/dev/LICENSE
*/

namespace App\Consumer;

use Hyperf\AsyncQueue\Process\ConsumerProcess;
Expand All @@ -10,5 +19,4 @@
#[Process(name: "async-queue")]
class PersonConsumer extends ConsumerProcess
{

}
42 changes: 15 additions & 27 deletions app/Controller/PersonController.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php

declare(strict_types=1);

/**
* This file is part of OpenCodeCo.
*
Expand All @@ -15,56 +16,44 @@
use App\Job\PersonJob;
use App\Model\Person;
use App\Request\PersonRequest;
use Hyperf\AsyncQueue\Driver\DriverFactory;
use Hyperf\AsyncQueue\Driver\DriverInterface;
use Hyperf\AsyncQueue\Driver\DriverInterface as QueueInterface;
use Hyperf\Cache\Cache as CacheInterface;
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
final readonly class PersonController
{
private DriverInterface $driver;

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

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

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

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

//
$this->queue->push(new PersonJob($person));

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

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

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

$person = json_decode($cached);

return $response->json($person);
if ($cached = $this->cache->get($id)) {
return $response->json(json_decode($cached));
}
$response->raw('Not found')->withStatus(404);

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

public function search(RequestInterface $request, ResponseInterface $response): MessageResponseInterface
Expand All @@ -85,7 +74,6 @@ public function search(RequestInterface $request, ResponseInterface $response):

public function count(RequestInterface $request, ResponseInterface $response): MessageResponseInterface
{
$count = Person::count();
return $response->json(['count' => $count]);
return $response->json(['count' => Person::count()]);
}
}
1 change: 1 addition & 0 deletions app/Exception/Handler/AppExceptionHandler.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php

declare(strict_types=1);

/**
* This file is part of OpenCodeCo.
*
Expand Down
20 changes: 13 additions & 7 deletions app/Job/PersonJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,28 @@

declare(strict_types=1);

/**
* This file is part of OpenCodeCo.
*
* @link https://github.com/opencodeco/rinha-de-backend-2023-q3
* @document https://github.com/opencodeco/rinha-de-backend-2023-q3/wiki
* @contact https://github.com/opencodeco/rinha-de-backend-2023-q3/discussions
* @license https://github.com/opencodeco/rinha-de-backend-2023-q3/blob/dev/LICENSE
*/

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 __construct(
public readonly array $params
) {
}

public function handle()
public function handle(): void
{
Db::table('person')->insert($this->params);
}
Expand Down
10 changes: 4 additions & 6 deletions app/Listener/DbQueryExecutedListener.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php

declare(strict_types=1);

/**
* This file is part of OpenCodeCo.
*
Expand All @@ -23,10 +24,7 @@
#[Listener]
class DbQueryExecutedListener implements ListenerInterface
{
/**
* @var LoggerInterface
*/
private $logger;
private LoggerInterface $logger;

public function __construct(ContainerInterface $container)
{
Expand All @@ -41,13 +39,13 @@ public function listen(): array
}

/**
* @param QueryExecuted $event
* @param QueryExecuted&object $event
*/
public function process(object $event): void
{
if ($event instanceof QueryExecuted) {
$sql = $event->sql;
if (! Arr::isAssoc($event->bindings)) {
if (!Arr::isAssoc($event->bindings)) {
$position = 0;
foreach ($event->bindings as $value) {
$position = strpos($sql, '?', $position);
Expand Down
1 change: 1 addition & 0 deletions app/Listener/ResumeExitCoordinatorListener.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php

declare(strict_types=1);

/**
* This file is part of OpenCodeCo.
*
Expand Down
1 change: 1 addition & 0 deletions app/Model/Model.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php

declare(strict_types=1);

/**
* This file is part of OpenCodeCo.
*
Expand Down
22 changes: 10 additions & 12 deletions app/Model/Person.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,25 @@

declare(strict_types=1);

/**
* This file is part of OpenCodeCo.
*
* @link https://github.com/opencodeco/rinha-de-backend-2023-q3
* @document https://github.com/opencodeco/rinha-de-backend-2023-q3/wiki
* @contact https://github.com/opencodeco/rinha-de-backend-2023-q3/discussions
* @license https://github.com/opencodeco/rinha-de-backend-2023-q3/blob/dev/LICENSE
*/

namespace App\Model;

use Hyperf\DbConnection\Model\Model;

/**
*/
class Person extends Model
{
public bool $timestamps = false;

/**
* The table associated with the model.
*/
protected ?string $table = 'person';

/**
* The attributes that are mass assignable.
*/
protected array $fillable = [
'id',
'nick',
Expand All @@ -28,14 +29,11 @@ class Person extends Model
'stack',
];

/**
* The attributes that should be cast to native types.
*/
protected array $casts = [
'id' => 'string',
'stack' => 'array'
];

protected array $attributes = [
'stack' => '[]',
];
Expand Down
10 changes: 4 additions & 6 deletions app/Request/PersonRequest.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php

declare(strict_types=1);

/**
* This file is part of OpenCodeCo.
*
Expand All @@ -12,23 +13,20 @@

namespace App\Request;

use App\Model\Person;
use Hyperf\Codec\Json;
use Hyperf\Validation\Request\FormRequest;
use Ramsey\Uuid\Uuid;

final class PersonRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}

/**
* Get the validation rules that apply to the request.
*
* @see https://github.com/zanfranceschi/rinha-de-backend-2023-q3/blob/main/INSTRUCOES.md#cria%C3%A7%C3%A3o-de-pessoas
*/
public function rules(): array
Expand All @@ -43,8 +41,8 @@ public function rules(): array

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

return [
'id' => Uuid::uuid4()->toString(),
'nick' => $data['apelido'],
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"description": "Swoole e Hyperf na Rinha de Back-end.",
"license": "MIT",
"require": {
"php": ">=8.0",
"php": ">=8.2",
"hyperf/async-queue": "^3.0",
"hyperf/cache": "^3.0",
"hyperf/command": "^3.0",
Expand Down
7 changes: 7 additions & 0 deletions config/autoload/dependencies.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php

declare(strict_types=1);

/**
* This file is part of OpenCodeCo.
*
Expand All @@ -9,5 +10,11 @@
* @contact https://github.com/opencodeco/rinha-de-backend-2023-q3/discussions
* @license https://github.com/opencodeco/rinha-de-backend-2023-q3/blob/dev/LICENSE
*/

use Hyperf\AsyncQueue\Driver\DriverFactory;
use Psr\Container\ContainerInterface;

return [
Hyperf\AsyncQueue\Driver\DriverInterface::class =>
fn (ContainerInterface $c) => $c->make(DriverFactory::class)->get('default')
];
2 changes: 2 additions & 0 deletions config/routes.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php

declare(strict_types=1);

/**
* This file is part of OpenCodeCo.
*
Expand All @@ -9,6 +10,7 @@
* @contact https://github.com/opencodeco/rinha-de-backend-2023-q3/discussions
* @license https://github.com/opencodeco/rinha-de-backend-2023-q3/blob/dev/LICENSE
*/

use App\Controller\PersonController;
use Hyperf\HttpServer\Router\Router;

Expand Down
22 changes: 22 additions & 0 deletions docs/user.rest
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
### Get user by id
GET http://localhost:9999/pessoas/1
Content-Type: application/json

### Count users
GET http://localhost:9999/contagem-pessoas
Content-Type: application/json

### Create user
POST http://localhost:9999/pessoas
Content-Type: application/json

{
"apelido": "José",
"nome": "José Roberto",
"nascimento": "2000-10-01",
"stack": [
"C#",
"Node",
"Oracle"
]
}
Loading

0 comments on commit 8abcb5f

Please sign in to comment.