KnowledgeServiceApi.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Http\Client\PendingRequest;
  4. use Illuminate\Http\Client\RequestException;
  5. use Illuminate\Support\Collection;
  6. use Illuminate\Support\Facades\Cache;
  7. use Illuminate\Support\Facades\Http;
  8. class KnowledgeServiceApi
  9. {
  10. public function __construct(
  11. protected readonly string $baseUrl = '',
  12. protected readonly int $timeout = 10,
  13. protected readonly int $cacheTtl = 300,
  14. ) {
  15. $this->baseUrl = rtrim($baseUrl ?: config('knowledge.base_url'), '/');
  16. $this->timeout = $timeout ?: (int) config('knowledge.timeout', 10);
  17. $this->cacheTtl = $cacheTtl ?: (int) config('knowledge.cache_ttl', 300);
  18. }
  19. /**
  20. * @return Collection<int, array<string, mixed>>
  21. */
  22. public function listKnowledgePoints(int $limit = 300): Collection
  23. {
  24. return Cache::remember(
  25. key: "knowledge-points-{$limit}",
  26. ttl: now()->addSeconds($this->cacheTtl),
  27. callback: fn () => collect($this->request('GET', '/knowledge-points', [
  28. 'limit' => $limit,
  29. ])),
  30. );
  31. }
  32. /**
  33. * @return array<string, mixed>
  34. */
  35. public function getKnowledgePointDetail(string $kpCode): array
  36. {
  37. return Cache::remember(
  38. key: "knowledge-point-detail-{$kpCode}",
  39. ttl: now()->addSeconds($this->cacheTtl),
  40. callback: fn () => $this->request('GET', "/graph/node/{$kpCode}"),
  41. );
  42. }
  43. /**
  44. * @return Collection<int, array<string, mixed>>
  45. */
  46. public function listSkills(?string $kpCode = null, int $limit = 200): Collection
  47. {
  48. return Cache::remember(
  49. key: "knowledge-skills-{$kpCode}-{$limit}",
  50. ttl: now()->addSeconds($this->cacheTtl),
  51. callback: fn () => collect($this->request('GET', '/skills', array_filter([
  52. 'kp_code' => $kpCode,
  53. 'limit' => $limit,
  54. ]))),
  55. );
  56. }
  57. /**
  58. * @throws RequestException
  59. * @return mixed
  60. */
  61. protected function request(string $method, string $path, array $params = []): mixed
  62. {
  63. $response = $this->http()->send($method, ltrim($path, '/'), [
  64. 'query' => $params,
  65. ]);
  66. return $response->throw()->json();
  67. }
  68. protected function http(): PendingRequest
  69. {
  70. return Http::baseUrl($this->baseUrl)
  71. ->acceptJson()
  72. ->timeout($this->timeout)
  73. ->retry(2, 200);
  74. }
  75. }