Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
2 tasks done
hax opened this issue Sep 20, 2023 · 2 comments
Open
2 tasks done

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

hax opened this issue Sep 20, 2023 · 2 comments

Comments

@hax
Copy link

hax commented Sep 20, 2023

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

  • I have searched through GitHub issues for similar issues.
  • I have completely read through the README and documentation.
@fengmk2
Copy link
Member

fengmk2 commented Sep 20, 2023

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

@iwanofski
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants