Skip to content

Commit

Permalink
refactor user controller
Browse files Browse the repository at this point in the history
  • Loading branch information
fokosun committed Sep 10, 2023
1 parent 9e101c1 commit 8825e0d
Show file tree
Hide file tree
Showing 5 changed files with 70 additions and 76 deletions.
7 changes: 5 additions & 2 deletions app/Console/Commands/LoginCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace App\Console\Commands;

use App\Models\User;
use App\Services\AuthService;
use App\Services\UserService;
use Illuminate\Console\Command;
Expand Down Expand Up @@ -39,17 +40,19 @@ public function handle(UserService $userService, AuthService $authService)

$fromCache = Cache::get('testUser');

$email = Str::random(5) . '@console.com';

if (!$fromCache) {
$this->line('User not found in Cache, creating new User ...');
$this->line('==============================================');

$response = $userService->store(new Request([
'name' => 'test user',
'email' => Str::random(5) . '@console.com',
'email' => $email,
'password' => 'testing123'
]));

$user = json_decode($response->getContent(), true)["response"]["data"];
$user = User::where('email', '=', $email)->first();

Cache::put('testUser', $user);
}
Expand Down
6 changes: 3 additions & 3 deletions app/Http/Controllers/SearchController.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
use App\Http\Requests\SearchRequest;
use App\Services\SearchService;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpFoundation\Response as ResponseAlias;

class SearchController extends Controller
{
Expand Down Expand Up @@ -132,7 +132,7 @@ public function getSearchResults(Request $request): \Illuminate\Http\JsonRespons

return response()->json([
'error', 'Your login session has expired. Please login.'
], Response::HTTP_UNAUTHORIZED);
], ResponseAlias::HTTP_UNAUTHORIZED);
}

if (str_starts_with($searchQuery, ":me|for-you")) {
Expand All @@ -144,7 +144,7 @@ public function getSearchResults(Request $request): \Illuminate\Http\JsonRespons

return response()->json([
'error', 'Your login session has expired. Please login.'
], Response::HTTP_UNAUTHORIZED);
], ResponseAlias::HTTP_UNAUTHORIZED);
}

if ($searchQuery === "cookbooks") {
Expand Down
3 changes: 2 additions & 1 deletion app/Http/Controllers/SubscriptionController.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use App\Models\Subscriber;
use Illuminate\Http\Response;
use Symfony\Component\HttpFoundation\Response as ResponseAlias;

class SubscriptionController extends Controller
{
Expand All @@ -31,7 +32,7 @@ public function store(\Illuminate\Http\Request $request)
'created' => true,
'data' => $subscriber,
],
], Response::HTTP_CREATED
], ResponseAlias::HTTP_CREATED
);
}
}
56 changes: 36 additions & 20 deletions app/Http/Controllers/UserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

namespace App\Http\Controllers;

use App\Exceptions\ApiException;
use App\Http\Requests\UserStoreRequest;
use App\Http\Requests\UserUpdateRequest;
use App\Mail\OtpWasGenerated;
Expand All @@ -16,10 +15,11 @@
use App\Services\TikTok\Videos;
use App\Services\UserService;
use Ichtrojan\Otp\Otp;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Symfony\Component\HttpFoundation\Response as ResponseAlias;
use Tymon\JWTAuth\Facades\JWTAuth;

class UserController extends Controller
Expand All @@ -31,32 +31,50 @@ public function __construct(UserService $service)
$this->service = $service;
}

public function index()
/**
* @return \Illuminate\Http\JsonResponse
*/
public function index(): JsonResponse
{
return $this->service->index();
return $this->successResponse(['data' => $this->service->index()]);
}

public function store(UserStoreRequest $request): \Illuminate\Http\JsonResponse
/**
* @param UserStoreRequest $request
* @return JsonResponse
*/
public function store(UserStoreRequest $request)
{
return $this->service->store($request);
return $this->service->store($request) ? $this->successResponse(
[
'response' => [
'created' => true,
'data' => [],
'status' => 'success'
]
],
ResponseAlias::HTTP_CREATED
) : $this->errorResponse(['error' => 'There was an error processing this request. Please try again.']);
}

public function show($username)
{
return $this->service->show($username);
return $this->successResponse(['data' => ['user' => $this->service->show($username)]]);
}

public function update($username, UserUpdateRequest $request)
{
if ($request->all()) {
$request->merge(['username']);
$request->merge(['username' => $username]);

return $this->service->update($request, $username);
if ($this->service->update($request, $username)) {
return $this->successResponse(['updated' => true, 'status' => 'success']);
}

return $this->errorResponse(['updated' => false, 'status' => 'failed']);
}

return response()->json([
'message' => 'nothing to update.',
]);
return response()->json(['message' => 'nothing to update.',]);
}

public function followUser(Request $request)
Expand All @@ -83,14 +101,14 @@ public function followUser(Request $request)

$following->save();

return response()->json($this->getWhoToFollowData($user), Response::HTTP_OK);
return response()->json($this->getWhoToFollowData($user), ResponseAlias::HTTP_OK);
}

return response()->noContent(Response::HTTP_OK);
return response()->noContent(ResponseAlias::HTTP_OK);
}
}

return response()->json(['error', 'Bad request.'], Response::HTTP_BAD_REQUEST);
return response()->json(['error', 'Bad request.'], ResponseAlias::HTTP_BAD_REQUEST);
}

return $this->unauthorizedResponse();
Expand All @@ -104,11 +122,9 @@ public function followUser(Request $request)
public function getWhoToFollow()
{
/** @phpstan-ignore-next-line */
if ($user = JWTAuth::parseToken()->user()) {
return $this->getWhoToFollowData($user);
}

return $this->unauthorizedResponse();
return ($user = JWTAuth::parseToken()->user()) ?
$this->getWhoToFollowData($user) :
$this->unauthorizedResponse();
}

private function getWhoToFollowData(User $user)
Expand Down
74 changes: 24 additions & 50 deletions app/Services/UserService.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,12 @@

namespace App\Services;

use App\Exceptions\CookbookModelNotFoundException;
use App\Interfaces\serviceInterface;
use App\Models\User;
use App\Models\UserContactDetail;
use App\Utils\DbHelper;
use Illuminate\Hashing\BcryptHasher;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

/**
* Class UserService
Expand All @@ -28,20 +26,13 @@ public function __construct()
*/
public function index()
{
$users = User::with('cookbooks', 'recipes', 'contact')->get();

return response([
'data' => $users,
], Response::HTTP_OK);
return User::with('cookbooks', 'recipes', 'contact')->get();
}

/**
* Create a new user
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\JsonResponse
* Create a new user resource
*/
public function store(Request $request): \Illuminate\Http\JsonResponse
public function store(Request $request)
{
$user = new User([
'name' => $request->name,
Expand All @@ -54,43 +45,35 @@ public function store(Request $request): \Illuminate\Http\JsonResponse
]);

$created = $user->save();
$serialized = $request->merge(['user_id' => $user->id]);
$contact = new UserContactDetailsService();
$contact->store(new Request($serialized->all()));

// dispatch(new SendEmailNotification($user->id));

return response()->json(
[
'response' => [
'created' => $created,
'data' => $user,
'status' => 'success',
],
], Response::HTTP_CREATED
);

if ($created) {
$serialized = $request->merge(['user_id' => $user->id]);

//TODO: hand this over to a job to handle asynchronously
$contact = new UserContactDetailsService();
$contact->store(new Request($serialized->all()));

// dispatch(new SendEmailNotification($user->id));
return true;
}

//TODO: log some debugging info here
return false;
}

/**
* @param $q
* @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|Response
* @throws CookbookModelNotFoundException
* @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
*/
public function show($q)
{
return response(
[
'data' => [
'user' => $this->findWhere($q)->get()->append(['tiktok_videos']),
],
], Response::HTTP_OK
);
return $this->findWhere($q)->get()->append(['tiktok_videos']);
}

/**
* @param Request $request
* @param string $option
* @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|Response
* @return bool
*/
public function update(Request $request, string $option)
{
Expand All @@ -115,21 +98,12 @@ public function update(Request $request, string $option)
}
}

if ($updated = $userRecord->save()) {
return response(
[
'updated' => (bool)$updated,
'status' => 'success',
], Response::HTTP_OK
);
}

throw new \Exception('Not saved.');
return $userRecord->save();
} catch (\Exception $e) {
return response([
'errors' => $e->getMessage(),
], Response::HTTP_BAD_REQUEST);
//TODO: log debugging message here
}

return false;
}

/**
Expand Down

0 comments on commit 8825e0d

Please sign in to comment.