Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HW20 API, CRUD, Resources #531

Open
wants to merge 1 commit into
base: VMeshavkin/hw18
Choose a base branch
from
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
98 changes: 98 additions & 0 deletions app/Http/Controllers/Api/Adverts/AdvertsController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
<?php

namespace App\Http\Controllers\Api\Adverts;

use App\Http\Controllers\Api\Adverts\Request\AdvertsListRequest;
use App\Http\Controllers\Api\Adverts\Resources\AdvertsResource;
use App\Http\Controllers\Api\Adverts\Resources\AdvertWithMessagesResource;
use App\Http\Controllers\Cms\Adverts\Request\StoreAdvertRequest;
use App\Http\Controllers\Controller;
use App\Models\Advert;
use App\Services\Adverts\AdvertsService;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class AdvertsController extends Controller
{
const MAX_PER_PAGE = 2;

/**
* @var AdvertsService
*/
private $advertsService;

public function __construct(AdvertsService $advertsService)
{

$this->advertsService = $advertsService;
}

/**
* Display a listing of the resource.
*
* @param AdvertsListRequest $request
* @return AdvertsResource
*/
public function index(AdvertsListRequest $request)
{

$limit = $request->getLimit();
$offset = $request->getOffset();

$adverts =$this->advertsService->pageApi($limit, $offset);

//return response()->json($adverts);
//return AdvertResource::collection($adverts);

return new AdvertsResource($adverts);

}

/**
* Store a newly created resource in storage.
*
* @param StoreAdvertRequest $request
* @return string
*/
public function store(StoreAdvertRequest $request)
{
$data = $request->getFormData();
$this->advertsService->storeAdvert($data);
return 'saved';
Copy link
Contributor

Choose a reason for hiding this comment

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

Можно сразу вернуть сохраненый ресурс

}

/**
* Display the specified resource.
*
* @param Advert $advert
* @return AdvertWithMessagesResource
*/
public function show(Advert $advert)
{
return new AdvertWithMessagesResource($advert);
}

/**
* Update the specified resource in storage.
*
* @param StoreAdvertRequest $request
* @param Advert $advert
* @return string
*/
public function update(StoreAdvertRequest $request, Advert $advert)
{
$this->advertsService->updateAdvert($advert, $request->all());
return 'Updated';
Copy link
Contributor

Choose a reason for hiding this comment

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

Можно сразу вернуть обновленый ресурсы это будет по REST

}

/**
* Remove the specified resource from storage.
*
* @param Advert $advert
* @return void
*/
public function destroy(Advert $advert)
{
$this->advertsService->deleteAdvert($advert);
}
}
32 changes: 32 additions & 0 deletions app/Http/Controllers/Api/Adverts/Request/AdvertsListRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php


namespace App\Http\Controllers\Api\Adverts\Request;


use Illuminate\Foundation\Http\FormRequest;

class AdvertsListRequest extends FormRequest
{

const MAX_PER_PAGE = 10;

public function rules()
{
return [
'limit' => 'nullable|integer|min:1|max:'.self::MAX_PER_PAGE,
'offset' => 'nullable|integer|min:0',
];
}

public function getLimit(): int
{
return $this->request->get('limit', self::MAX_PER_PAGE);
}

public function getOffset(): int
{
return $this->request->get('offset', 0);
}

}
26 changes: 26 additions & 0 deletions app/Http/Controllers/Api/Adverts/Resources/AdvertResource.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

namespace App\Http\Controllers\Api\Adverts\Resources;

use App\Models\Advert;
use App\Http\Controllers\Api\Adverts\Request\AdvertsListRequest;
use Illuminate\Http\Resources\Json\JsonResource;

/**
* Class AdvertResource
* @package App\Http\Controllers\Api\Adverts\Resources
* @mixin Advert
*/
class AdvertResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param AdvertsListRequest $request
* @return array
*/
public function toArray($request)
{
return parent::toArray($request);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

namespace App\Http\Controllers\Api\Adverts\Resources;

use App\Models\Advert;
use Illuminate\Http\Resources\Json\JsonResource;

/**
* Class AdvertResource
* @package App\Http\Controllers\Api\Adverts\Resources
* @mixin Advert
*/
class AdvertWithMessagesResource extends AdvertResource
{
/**
* Transform the resource into an array.
*
* @param Request $request
* @return array
*/
public function toArray($request)
{
$data = parent::toArray($request);

$owner = $this->user->name;
$town = $this->town->name;
$division = $this->division->name;

$messages = $this->messages;

$messagesData = [];
foreach ($messages as $message) {
$messagesData[] = ['userId' => $message->user_id, 'content' => $message->content];
}

$data['owner'] = $owner;
$data['town'] = $town;
$data['division'] = $division;
$data['messages'] = $messagesData;

return $data;


// return [
// 'id' => $this->id,
// 'title' => $this->title,
// ];

}
}
27 changes: 27 additions & 0 deletions app/Http/Controllers/Api/Adverts/Resources/AdvertsResource.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace App\Http\Controllers\Api\Adverts\Resources;

use App\Http\Controllers\Api\Adverts\Request\AdvertsListRequest;
use App\Models\Advert;
use Illuminate\Http\Resources\Json\ResourceCollection;
use Illuminate\Support\Str;


class AdvertsResource extends ResourceCollection
{
/**
* Transform the resource into an array.
*
* @param AdvertsListRequest $request
* @return array
*/
public function toArray($request)
{
return [
'data' => AdvertResource::collection($this),
//'limit' => $request->get('limit'),
// 'token' => Str::random(80),
];
}
}
34 changes: 34 additions & 0 deletions app/Http/Controllers/Auth/ApiTokenController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php


namespace App\Http\Controllers\Auth;


use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class ApiTokenController extends Controller
{

/**
* Update the authenticated user's API token.
*
* @param Request $request
* @return array
*/
public function update(Request $request)
{
$token = Str::random(80);

$request->user()->forceFill([
'api_token' => hash('sha256', $token),
])->save();

return ['token' => $token];
}

// незабыть поменять в auth.php в 'guards'-->'api' --> 'hash' => true,


}
2 changes: 2 additions & 0 deletions app/Http/Controllers/Auth/RegisterController.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class RegisterController extends Controller
{
Expand Down Expand Up @@ -69,6 +70,7 @@ protected function create(array $data)
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'api_token' => Str::random(80),
]);
}
}
5 changes: 5 additions & 0 deletions app/Services/Adverts/AdvertsService.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ public function showTownList()
return ItemsDTO::make($town);
}

public function pageApi(int $limit, int $offset)
{
return $this->advertCacheRepository->cachingPageApi($limit, $offset);
}

public function page($qty)
{
// return $this->advertCacheRepository->cachingPage($qty);
Expand Down
11 changes: 11 additions & 0 deletions app/Services/Adverts/Repositories/AdvertCacheRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,15 @@ public function cachingPage($qty)

}

public function cachingPageApi(int $limit, int $offset)
{

$cacheKey = self::PAGE_CACHE_KEY.$limit.'_'.$offset; //вынести в класс-генератор ключа, генерит ключ под запрос, незабыть в пргреве

return \Cache::remember($cacheKey, self::CACHE_TIME, function() use($limit, $offset){
return $this->advertRepository->paginateListApi($limit, $offset);
});

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ public function divisionList();
public function townList();

public function paginateList($qty);
public function paginateListApi(int $limit, int $offset);

public function createFromArray(array $data): Advert;

Expand Down
10 changes: 10 additions & 0 deletions app/Services/Adverts/Repositories/EloquentAdvertRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,16 @@ public function paginateList($qty)
return Advert::with('town', 'user', 'division')->paginate($qty);
}

public function paginateListApi(int $limit, int $offset)
Copy link
Contributor

Choose a reason for hiding this comment

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

Я бы предложил переименовать метод в getAdverts(int $limit, int $offset)
a with сделал бы в сервисе,

$adverts = $this->repository->getAdverts
$adverts->load(['town', 'user', 'division', 'messages'])

{
$advert = Advert::query();
if ($limit) $advert->take($limit);
if($offset) $advert->skip($offset);

$advert->with('town', 'user', 'division');
Copy link
Contributor

Choose a reason for hiding this comment

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

messages зависимость тоже используете

return $advert->get(['adverts.*']); // ???
Copy link
Contributor

Choose a reason for hiding this comment

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

Если у вас будут join в запросе, то можете вернуть лишнее данные, это зашита от дурака)

}

public function createFromArray(array $data): Advert
{
// $advert = new Advert();
Expand Down
1 change: 1 addition & 0 deletions database/factories/UserFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
'role'=>'user',
'email_verified_at' => now(),
'password' => Hash::make(123), //'password' => bcrypt('123'),
'api_token' => Str::random(20),
'remember_token' => Str::random(10),
];
});
38 changes: 38 additions & 0 deletions database/migrations/2020_07_23_120756_add_api_token_to_user.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddApiTokenToUser extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{

Schema::table('users', function (Blueprint $table) {
$table->string('api_token', 80)->after('password')
->unique()
->nullable()
->default(null);
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('user', function (Blueprint $table) {
$table->dropColumn(['api_token']);
});


}
}
Loading