1
+ import qs from "qs"
2
+ import * as auth from 'auth-provider'
3
+ import { useAuth } from "../context/auth-context" ;
4
+
5
+ const apiUrl = process . env . REACT_APP_API_URL
6
+
7
+ interface Config extends RequestInit {
8
+ token ?: string ;
9
+ data ?: object ;
10
+ }
11
+
12
+ export const http = async ( endpoint : string , { data, token, headers, ...customConfig } : Config = { } ) => {
13
+ const config = {
14
+ method : 'GET' , //默认值为GET 如果customConfig有method传进来就会覆盖掉这里的值
15
+ headers : {
16
+ Authorization : token ? `Bearer ${ token } ` : '' ,
17
+ 'Content-Type' : data ? 'application/json' : ''
18
+ } ,
19
+ ...customConfig
20
+ }
21
+
22
+ if ( config . method . toUpperCase ( ) === 'GET' ) {
23
+ endpoint += `?${ qs . stringify ( data ) } `
24
+ } else {
25
+ config . body = JSON . stringify ( data || { } )
26
+ }
27
+
28
+ return window . fetch ( `${ apiUrl } /${ endpoint } ` , config ) . then ( async res => {
29
+ //token过期的时候
30
+ if ( res . status === 401 ) {
31
+ await auth . logout ( ) //退出重新登录
32
+ window . location . reload ( ) //页面刷新
33
+ return Promise . reject ( { message : '请重新登录' } )
34
+ }
35
+ const data = await res . json ( )
36
+ if ( res . ok ) {
37
+ return data
38
+ } else {
39
+ return Promise . reject ( data )
40
+ }
41
+ } )
42
+ }
43
+
44
+ //只有Hook里面可以使用其他的Hook
45
+ export const useHttp = ( ) => {
46
+ const { user} = useAuth ( )
47
+ //utility type的用法:用泛型给它传入一个其它类型,然后utility type对这个类型进行某种操作
48
+ return ( ...[ endpoint , config ] : Parameters < typeof http > ) => http ( endpoint , { ...config , token : user ?. token } )
49
+ }
0 commit comments