@nsnanocat/util 1.8.7 → 1.8.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/polyfill/fetch.mjs +36 -29
package/package.json
CHANGED
package/polyfill/fetch.mjs
CHANGED
|
@@ -159,37 +159,44 @@ export async function fetch(resource, options = {}) {
|
|
|
159
159
|
}),
|
|
160
160
|
]);
|
|
161
161
|
case "Node.js": {
|
|
162
|
-
const
|
|
163
|
-
const
|
|
164
|
-
const
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
if (undefined === resource.headers.Cookie && undefined === resource.cookieJar) resource.cookieJar = ckjar;
|
|
169
|
-
}
|
|
162
|
+
const nodeFetch = globalThis.fetch ? globalThis.fetch : require("node-fetch");
|
|
163
|
+
const fetchCookie = globalThis.fetchCookie ? globalThis.fetchCookie : require("fetch-cookie").default;
|
|
164
|
+
const fetch = fetchCookie(nodeFetch);
|
|
165
|
+
// 转换请求参数
|
|
166
|
+
resource.timeout = resource.timeout * 1000;
|
|
167
|
+
resource.redirect = resource.redirection ? "follow" : "manual";
|
|
170
168
|
const { url, ...options } = resource;
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
169
|
+
// 发送请求
|
|
170
|
+
return Promise.race([
|
|
171
|
+
await fetch(url, options)
|
|
172
|
+
.then(async response => {
|
|
173
|
+
const bodyBytes = await response.arrayBuffer();
|
|
174
|
+
let headers;
|
|
175
|
+
try {
|
|
176
|
+
headers = response.headers.raw();
|
|
177
|
+
} catch {
|
|
178
|
+
headers = Array.from(response.headers.entries()).reduce((acc, [key, value]) => {
|
|
179
|
+
acc[key] = acc[key] ? [...acc[key], value] : [value];
|
|
180
|
+
return acc;
|
|
181
|
+
}, {});
|
|
178
182
|
}
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
183
|
+
return {
|
|
184
|
+
ok: response.ok ?? /^2\d\d$/.test(response.status),
|
|
185
|
+
status: response.status,
|
|
186
|
+
statusCode: response.status,
|
|
187
|
+
statusText: response.statusText,
|
|
188
|
+
body: bodyBytes.toString("utf-8"),
|
|
189
|
+
bodyBytes: bodyBytes,
|
|
190
|
+
headers: Object.fromEntries(Object.entries(headers).map(([key, value]) => [key, key.toLowerCase() !== "set-cookie" ? value.toString() : value])),
|
|
191
|
+
};
|
|
192
|
+
})
|
|
193
|
+
.catch(error => Promise.reject(error.message)),
|
|
194
|
+
new Promise((resolve, reject) => {
|
|
195
|
+
setTimeout(() => {
|
|
196
|
+
reject(new Error(`${Function.name}: 请求超时, 请检查网络后重试`));
|
|
197
|
+
}, resource.timeout);
|
|
198
|
+
}),
|
|
199
|
+
]);
|
|
193
200
|
}
|
|
194
201
|
}
|
|
195
202
|
}
|