| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- <?php
- namespace App\Services;
- use Illuminate\Http\Client\PendingRequest;
- use Illuminate\Http\Client\RequestException;
- use Illuminate\Support\Collection;
- use Illuminate\Support\Facades\Cache;
- use Illuminate\Support\Facades\Http;
- class KnowledgeServiceApi
- {
- public function __construct(
- protected readonly string $baseUrl = '',
- protected readonly int $timeout = 10,
- protected readonly int $cacheTtl = 300,
- ) {
- $this->baseUrl = rtrim($baseUrl ?: config('knowledge.base_url'), '/');
- $this->timeout = $timeout ?: (int) config('knowledge.timeout', 10);
- $this->cacheTtl = $cacheTtl ?: (int) config('knowledge.cache_ttl', 300);
- }
- /**
- * @return Collection<int, array<string, mixed>>
- */
- public function listKnowledgePoints(int $limit = 300): Collection
- {
- return Cache::remember(
- key: "knowledge-points-{$limit}",
- ttl: now()->addSeconds($this->cacheTtl),
- callback: fn () => collect($this->request('GET', '/knowledge-points', [
- 'limit' => $limit,
- ])),
- );
- }
- /**
- * @return array<string, mixed>
- */
- public function getKnowledgePointDetail(string $kpCode): array
- {
- return Cache::remember(
- key: "knowledge-point-detail-{$kpCode}",
- ttl: now()->addSeconds($this->cacheTtl),
- callback: fn () => $this->request('GET', "/graph/node/{$kpCode}"),
- );
- }
- /**
- * @return Collection<int, array<string, mixed>>
- */
- public function listSkills(?string $kpCode = null, int $limit = 200): Collection
- {
- return Cache::remember(
- key: "knowledge-skills-{$kpCode}-{$limit}",
- ttl: now()->addSeconds($this->cacheTtl),
- callback: fn () => collect($this->request('GET', '/skills', array_filter([
- 'kp_code' => $kpCode,
- 'limit' => $limit,
- ]))),
- );
- }
- /**
- * @throws RequestException
- * @return mixed
- */
- protected function request(string $method, string $path, array $params = []): mixed
- {
- $response = $this->http()->send($method, ltrim($path, '/'), [
- 'query' => $params,
- ]);
- return $response->throw()->json();
- }
- protected function http(): PendingRequest
- {
- return Http::baseUrl($this->baseUrl)
- ->acceptJson()
- ->timeout($this->timeout)
- ->retry(2, 200);
- }
- }
|