(url: string, config?: RequestInit, nothen?: boolean)
| 81 | } |
| 82 | |
| 83 | request(url: string, config?: RequestInit, nothen?: boolean) { |
| 84 | config = config || {}; |
| 85 | const headers = <Headers>config.headers || new Headers(); |
| 86 | headers.set(`Authorization`, `Bearer ${this.accessToken}`); |
| 87 | config.headers = headers; |
| 88 | const doFetch = () => fetch(url, config); |
| 89 | const retryWithFreshToken = async () => { |
| 90 | const token = await AuthVerify("dropbox", true); |
| 91 | this.accessToken = token; |
| 92 | headers.set(`Authorization`, `Bearer ${this.accessToken}`); |
| 93 | return doFetch(); |
| 94 | }; |
| 95 | if (nothen) { |
| 96 | return doFetch().then(async (resp) => { |
| 97 | if (resp.status === 401) { |
| 98 | return retryWithFreshToken(); |
| 99 | } |
| 100 | return resp; |
| 101 | }); |
| 102 | } |
| 103 | return doFetch() |
| 104 | .then(async (response) => { |
| 105 | if (response.status === 401) { |
| 106 | response = await retryWithFreshToken(); |
| 107 | } |
| 108 | if (!response.ok) { |
| 109 | const errorText = await response.text(); |
| 110 | throw new Error(`Dropbox API Error: ${response.status} - ${errorText}`); |
| 111 | } |
| 112 | return response.json(); |
| 113 | }) |
| 114 | .then(async (data) => { |
| 115 | if (data.error) { |
| 116 | if (data.error[".tag"] === "invalid_access_token") { |
| 117 | // Token可能过期,尝试刷新 |
| 118 | const token = await AuthVerify("dropbox", true); |
| 119 | this.accessToken = token; |
| 120 | headers.set(`Authorization`, `Bearer ${this.accessToken}`); |
| 121 | return fetch(url, config) |
| 122 | .then(async (retryResponse) => { |
| 123 | if (!retryResponse.ok) { |
| 124 | const errorText = await retryResponse.text(); |
| 125 | throw new Error(`Dropbox API Error: ${retryResponse.status} - ${errorText}`); |
| 126 | } |
| 127 | return retryResponse.json(); |
| 128 | }) |
| 129 | .then((retryData) => { |
| 130 | if (retryData.error) { |
| 131 | throw new Error(JSON.stringify(retryData)); |
| 132 | } |
| 133 | return retryData; |
| 134 | }); |
| 135 | } |
| 136 | throw new Error(JSON.stringify(data)); |
| 137 | } |
| 138 | return data; |
| 139 | }); |
| 140 | } |
no test coverage detected