GlossaryController.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace App\Http\Controllers\V3;
  3. use App\Http\Controllers\Controller;
  4. use App\Http\Requests\V3\IndexGlossaryRequest;
  5. use App\Http\Resources\V3\GlossaryEntryResource;
  6. use App\Services\V3\GlossaryService;
  7. use Illuminate\Http\Response;
  8. /**
  9. * 术语词汇表:语法术语表 / 社区译名表(只读)。
  10. *
  11. * 取代 `GET /v2/term-vocabulary?view=grammar|community`(`TermVocabularyController@index`)。
  12. * v2 那份在 dashboard-v4 下线前原样保留,不要改动。
  13. */
  14. class GlossaryController extends Controller
  15. {
  16. public function __construct(private readonly GlossaryService $glossaries) {}
  17. /**
  18. * 术语词汇表
  19. *
  20. * 整表返回、不分页(客户端启动时拉一次,本地查词)。`meta.lang` 是实际用到的语言:
  21. * 该语言没有这张表时回退到英文。条目的 `id`(术语 guid)只有 grammar 表给,community 表不给(省流量)。
  22. *
  23. * @unauthenticated
  24. *
  25. * @urlParam kind string required 哪张表:grammar 语法术语,community 社区译名。Enum: grammar,community
  26. *
  27. * @queryParam lang string 语言,如 zh-Hans。缺省用界面语言(Accept-Language 协商的结果)
  28. *
  29. * @meta kind string 哪张表
  30. * @meta lang string 实际用到的语言(没有该语言的表时是 en)
  31. * community 表带 `ETag`(`Cache-Control: public, no-cache`):浏览器下次自动带 `If-None-Match`,
  32. * 表没变就回 304、不带正文。ETag 在社区术语任务每次跑完时更换。grammar 表暂不带。
  33. * @meta total integer 条数
  34. */
  35. public function __invoke(IndexGlossaryRequest $request, string $kind)
  36. {
  37. $lang = $request->validated('lang') ?? app()->getLocale();
  38. $etag = $this->glossaries->etag($kind, $lang);
  39. $withEtag = fn ($response) => $etag === null ? $response : $response
  40. ->setEtag($etag)
  41. ->header('Cache-Control', 'public, no-cache');
  42. // 表没变:在查整表之前就回 304(isNotModified 按 RFC 9110 弱比较,nginx 压缩后的 W/"…" 也认)
  43. if ($etag !== null) {
  44. $probe = $withEtag(new Response);
  45. if ($probe->isNotModified($request)) {
  46. return $probe;
  47. }
  48. }
  49. $result = $this->glossaries->entries($kind, $lang);
  50. return $withEtag(GlossaryEntryResource::collection($result['items'])->additional(['meta' => [
  51. 'kind' => $kind,
  52. 'lang' => $result['lang'],
  53. 'total' => $result['items']->count(),
  54. ]])->response());
  55. }
  56. }