You need to enable JavaScript to run this app.
导航
请求聚合
最近更新时间:2024.04.09 14:14:16首次发布时间:2023.02.15 19:04:51

以下示例展示了如何将多个不同的源站回复汇聚到一个回复中。

async function aggRequest(urlBase, urlQuery, writable) {
  const path_list = urlQuery.split(',');
  let preventClose = true;
  const size = path_list.length;
  let idx = 0;

  for (const p of path_list) {
    const u = urlBase + p;
    const req = await fetch(urlBase + p);
    if (idx == (size - 1)) preventClose = false;

    // 开始将数据pipe到对应的writable中,那么readable就可以读出数据
    await req.body.pipeTo(writable, {preventClose});

    // 编写footer,帮助识别各种回复
    if (preventClose) {
      const writer = writable.getWriter();
      await writer.write(
    `\n\n<!-- This is from ${u} ------------------------------>\n\n`);
      writer.releaseLock();
    }
    ++idx;
  }
}

async function handle(event) {
  const url = new URL(event.request.url);
  const {readable, writable} = new TransformStream();

  aggRequest(
      url.protocol + '//' + url.hostname + '/', url.search.substring(1),
      writable);
      
  return new Response(readable);
}

addEventListener('fetch', (event) => {
  event.respondWith(handle(event));
});