koa icon indicating copy to clipboard operation
koa copied to clipboard

[feat] Support Web (WHATWG) stream, Blob and Response

Open hax opened this issue 1 year ago • 2 comments

Describe the feature

Currently response.body= or ctx.body= support buffers, strings and Nodejs streams. I suggest we also add support to Web stream, Blob and Response (currently just fallback to json which break users expectation), maybe also all async iterables, Nodejs already have those APIs in global.

This is my workaround, it works but it's better to support them in the core.

app.use(async (ctx, next) => {
    await next();
    // Note: need to clear type before set body, or the type might always be json
    // See Koa impl: https://github.com/koajs/koa/blob/dbf4b8f41286befd53dfd802740f2021441435bf/lib/response.js#L134-L190
    if (ctx.body instanceof ReadableStream) {
        ctx.type = "";
        ctx.body = Readable.fromWeb(ctx.body);
    } else if (ctx.body instanceof Blob) {
        const blob = ctx.body;
        ctx.type = blob.type;
        ctx.length = blob.size;
        ctx.body = Readable.fromWeb(blob.stream());
    } else if (ctx.body instanceof Response) {
        const response = ctx.body;
        ctx.status = response.status;
        ctx.type = "";
        // Note: don't clear all headers so the headers added by middlewares still effective
        for (const [name, value] of response.headers) ctx.set(name, value);
        if (response.redirected) ctx.redirect(response.url);
        else ctx.body = Readable.fromWeb(response.body);
    }
    // maybe we could also support all async iterables
    // else if (ctx.body[Symbol.asyncIterator]) {
    //   ctx.type = ""; ctx.body = Readable.from(ctx.body);
    // }
});

Checklist

  • [x] I have searched through GitHub issues for similar issues.
  • [x] I have completely read through the README and documentation.

hax avatar Sep 20 '23 05:09 hax

@hax Cool! Please send us a pull request, we love to merge it!

fengmk2 avatar Sep 20 '23 07:09 fengmk2

I support this, especially if its additive only (i.e. no breaking)

iwanofski avatar Sep 21 '23 09:09 iwanofski

@fengmk2 have any plan to support this feature?

image72 avatar Jun 13 '24 16:06 image72

@fengmk2 have any plan to support this feature?

@hax has given the implementation code and you are welcome to submit a pull request.

fengmk2 avatar Jun 14 '24 01:06 fengmk2

Will have a PR for it soon

TommyDew42 avatar Jun 18 '24 17:06 TommyDew42

@fengmk2 i've done a PR for this i'm open to suggestions for improvement 😉

kravorkid avatar Jun 25 '24 17:06 kravorkid