Lae/app/Http/Controllers/Api/ForumController.php

65 lines
1.5 KiB
PHP
Raw Normal View History

2022-09-16 13:07:05 +00:00
<?php
2022-11-06 11:28:22 +00:00
namespace App\Http\Controllers\Api;
2022-09-16 13:07:05 +00:00
2022-11-06 11:28:22 +00:00
use App\Http\Controllers\Controller;
2022-09-16 13:07:05 +00:00
use Closure;
2022-11-20 13:45:07 +00:00
use Illuminate\Http\Client\PendingRequest;
2023-01-10 13:42:27 +00:00
use Illuminate\Http\JsonResponse;
2022-11-06 11:28:22 +00:00
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use function config;
2022-09-16 13:07:05 +00:00
class ForumController extends Controller
{
2022-11-20 13:45:07 +00:00
private mixed $baseUrl;
private PendingRequest $http;
2022-09-16 13:07:05 +00:00
public function __construct()
{
$this->baseUrl = config('forum.base_url');
$this->http = Http::baseUrl($this->baseUrl . '/api')->throw();
}
2023-01-10 13:42:27 +00:00
public function announcements(): JsonResponse
2022-09-16 13:07:05 +00:00
{
$resp = $this->cache(function () {
2022-09-20 04:13:49 +00:00
return $this->get('discussions?filter[tag]=announcements&page[offset]=0&sort=-createdAt');
2022-09-16 13:07:05 +00:00
});
2022-09-16 13:36:13 +00:00
return $this->resp($resp);
2022-09-16 13:07:05 +00:00
}
public function cache(Closure $callback)
{
// 获取调用方法名
$method = debug_backtrace()[1]['function'];
return Cache::remember('forum.func.' . $method, 60, function () use ($callback) {
2022-09-16 13:07:05 +00:00
return $callback();
});
}
2022-09-16 13:36:13 +00:00
public function get($url)
{
2022-11-20 14:35:53 +00:00
return $this->http->get($url)->json()['data'];
}
2022-09-16 13:36:13 +00:00
2023-01-10 13:42:27 +00:00
public function resp($data): JsonResponse
2022-09-18 08:21:24 +00:00
{
2022-09-16 13:36:13 +00:00
$data['base_url'] = $this->baseUrl;
return $this->success($data);
}
2023-01-10 13:42:27 +00:00
public function pinned(): JsonResponse
{
$resp = $this->cache(function () {
return $this->get('discussions?filter[tag]=pinned&page[offset]=0&sort=-createdAt');
});
return $this->resp($resp);
}
2022-09-16 13:07:05 +00:00
}