Browse Source

✨ feat(request): 增强请求功能,支持查询参数和可选身份验证

陈雪 3 weeks ago
parent
commit
b9dc87dce4
2 changed files with 21 additions and 2 deletions
  1. 12 2
      src/utils/request.ts
  2. 9 0
      src/vite-env.d.ts

+ 12 - 2
src/utils/request.ts

@@ -1,15 +1,25 @@
+import { useUserStore } from '@/store/user'
 import { fetch } from '@tauri-apps/plugin-http'
 
 interface RequestOptions {
   method: 'GET' | 'POST' | 'PUT' | 'DELETE'
   url: string
+  query?: Record<string, string>
+  noAuth?: boolean
   headers?: Record<string, string>
   body?: unknown
 }
 
-export const request = async ({ method, url, headers, body }: RequestOptions) => {
+export const request = async ({ method, url, headers, body, noAuth, query }: RequestOptions) => {
+  if (!noAuth) {
+    const { getToken } = useUserStore()
+    headers['Access-Token'] = getToken
+  }
+  const reqPath = new URL(url, import.meta.env.VITE_BASE_URL || '')
+  if (query) Object.keys(query).forEach((key) => reqPath.searchParams.append(key, query[key]))
+
   try {
-    const response = await fetch(url, {
+    const response = await fetch(reqPath.toString(), {
       method,
       headers,
       body: body ? JSON.stringify(body) : undefined,

+ 9 - 0
src/vite-env.d.ts

@@ -0,0 +1,9 @@
+/// <reference types="vite/client" />
+
+interface ImportMetaEnv {
+  readonly VITE_BASE_URL?: string
+}
+
+interface ImportMeta {
+  readonly env: ImportMetaEnv
+}