Skip to content

网络请求.js ​

查看原文件

js
import { http, files, websocket } from '@kodet/core';

/** 标准 Request 负责 URL、方法、请求头、正文、缓存、跳转、credentials 与 signal。
 * fetch 的 4xx/5xx 仍返回 Response;网络失败为 TypeError,取消保留 signal.reason。
 * Response 正文单次消费;不用的正文在未锁定时 cancel,读流的 finally 取消 reader 并 releaseLock。
 */
const request = new Request('https://example.invalid/api/items?page=1', {
    method: 'POST', headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ title: '示例' }), redirect: 'follow', credentials: 'omit',
});

/** 工厂只绑定宿主传输能力,返回标准 (input, init?) => Promise<Response> 函数。
 * session 只选择 Cookie jar,必须 credentials:'include' 才自动收发;same-origin/omit 不自动带 Cookie。
 * 查询参数使用 URLSearchParams,请求 JSON 使用 JSON.stringify,取消使用 AbortSignal。
 */
const account = http.session('account', { persistent: true });
const accountFetch = http.createFetch({
    session: account,
    timeoutMs: 0, connectTimeoutMs: 15000, idleTimeoutMs: 15000,
    maxResponseBytes: 128 * 1024 * 1024, maxBufferBytes: 32 * 1024 * 1024,
    maxRedirects: 10, allowHttpsDowngrade: false, sensitiveHeaders: ['x-account-token'],
    onDownloadProgress: progress => { void progress.bytes; void progress.total; },
});

/** 原生原子文件下载:标准 Request 传 signal/headers/credentials,宿主选项传续传、校验和限额。
 * @param {string} url @param {AbortSignal} signal @param {string} sha256
 */
export async function download(url, signal, sha256) {
    return http.download(new Request(url, { signal, credentials: 'include' }), files.data.file('download.bin'), {
        session: account, resume: true, sha256, maxBytes: 128 * 1024 * 1024,
    });
}

/** WebSocket 默认用标准全局构造器;需要额外握手能力时仍得到同一种标准对象。
 * @param {string} url @param {AbortSignal} signal
 */
export function connect(url, signal) {
    const socket = websocket.connect(url, { headers: { 'x-account': 'example' }, protocols: ['chat'], connectTimeoutMs: 15000, signal });
    socket.onmessage = event => { void event.data; };
    return socket;
}
void request; void accountFetch;