@@ -3,6 +3,15 @@ import type { ApiResponse } from '../types/auth'
33const SUCCESS_CODE = 0
44const ACCESS_TOKEN_STORAGE_KEY = 'yunyu_access_token'
55
6+ /**
7+ * 前端接口请求选项。
8+ * 作用:在保留 `$fetch` 原生能力的基础上,补充是否自动附带访问令牌的控制项,
9+ * 便于登录、注册等匿名接口显式跳过 Bearer Token 请求头。
10+ */
11+ interface ApiClientRequestOptions < T > extends Parameters < typeof $fetch < T > > [ 1 ] {
12+ withAuth ?: boolean
13+ }
14+
615/**
716 * 前端接口客户端。
817 * 作用:为前端页面和业务组合式函数提供统一请求入口,
@@ -62,12 +71,14 @@ export function useApiClient() {
6271 * @param headersInit 原始请求头配置
6372 * @returns 最终请求头对象
6473 */
65- function buildHeaders ( headersInit ?: HeadersInit ) {
66- hydratePersistedAccessToken ( )
74+ function buildHeaders ( headersInit ?: HeadersInit , withAuth = true ) {
75+ if ( withAuth ) {
76+ hydratePersistedAccessToken ( )
77+ }
6778
6879 const headers = new Headers ( headersInit || { } )
6980
70- if ( accessToken . value ) {
81+ if ( withAuth && accessToken . value ) {
7182 headers . set ( 'Authorization' , `Bearer ${ accessToken . value } ` )
7283 }
7384
@@ -81,13 +92,14 @@ export function useApiClient() {
8192 */
8293 async function request < T > (
8394 path : string ,
84- options : Parameters < typeof $fetch < T > > [ 1 ] = { }
95+ options : ApiClientRequestOptions < T > = { }
8596 ) {
86- const headers = buildHeaders ( options . headers )
97+ const { withAuth = true , ...fetchOptions } = options
98+ const headers = buildHeaders ( fetchOptions . headers , withAuth )
8799
88100 try {
89101 const response = await $fetch < ApiResponse < T > > ( `${ config . public . apiBase } ${ path } ` , {
90- ...options ,
102+ ...fetchOptions ,
91103 headers
92104 } )
93105
@@ -122,13 +134,14 @@ export function useApiClient() {
122134 */
123135 async function rawRequest < T > (
124136 path : string ,
125- options : Parameters < typeof $fetch < T > > [ 1 ] = { }
137+ options : ApiClientRequestOptions < T > = { }
126138 ) {
127- const headers = buildHeaders ( options . headers )
139+ const { withAuth = true , ...fetchOptions } = options
140+ const headers = buildHeaders ( fetchOptions . headers , withAuth )
128141
129142 try {
130143 return await $fetch < T > ( `${ config . public . apiBase } ${ path } ` , {
131- ...options ,
144+ ...fetchOptions ,
132145 headers
133146 } )
134147 } catch ( error : any ) {
0 commit comments