Untitled

mail@pastecode.io avatar
unknown
php
a year ago
1.5 kB
32
Indexable
Never
<?php namespace Api\Controllers;
use Http\Request;
use Http\Http;
class UserController extends Controller{
    public function getUsers(Request $request): array    {
        if(cache()->has('api.users')) {
            return ['data' => cache()->get('api.users')];
        }
        $response = Http::get('https://apiurl.com/users');
        if ($response->ok()) {
            $data = $response->json();
            $users = array_map(fn ($user) => [
                'id' => $user['id'],
                'first_name' => $user['name'],
                'last_name' => $user['surname'],
            ], $data);
            cache()->set('api.users', $users);
            return ['data' => $users];
        } else {
            return ['status' => 'error'];
        }
    }
    public function getUser(Request $request, $id): array    {
        if(cache()->has("api.user.{$id}")) {
            return ['data' => cache()->get("api.user.{$id}")];
        }
        $response = Http::get("https://apiurl.com/users/{$id}");
        if ($response->ok()) {
            $data = $response->json();
            $user = [
                'id' => $data['id'],
                'first_name' => $data['name'],
                'last_name' => $data['surname'],
            ];
            cache()->set("api.user.{$id}", $user);
            return ['data' => $user];
        } else {
            return ['status' => 'error'];
        }
    }
}