crossws
crossws copied to clipboard
Using crossws sse with expressjs frameworks (Nestjs)
Describe the change
Is there a standard/recommended way to convert the express req object to web standard that works with crossws sse.
This is my current implementation
// utils/web-standard.ts
import { Request as ExpressRequest, Response as ExpressResponse } from 'express';
import { Readable } from 'stream';
export function toWebRequest(req: ExpressRequest): Request {
const url = `${req.protocol}://${req.get('host')}${req.originalUrl}`;
const body = ['GET', 'HEAD'].includes(req.method) ? undefined : Readable.toWeb(req).body;
return new Request(url, {
method: req.method,
headers: req.headers as HeadersInit,
body,
});
}
export async function sendWebResponseToExpress(res: ExpressResponse, webRes: Response) {
res.status(webRes.status);
webRes.headers.forEach((value, key) => {
res.setHeader(key, value);
});
if (webRes.body) {
const reader = webRes.body.getReader();
const stream = new ReadableStream({
async start(controller) {
while (true) {
const { done, value } = await reader.read();
if (done) break;
controller.enqueue(value);
}
controller.close();
}
});
const readable = Readable.fromWeb(stream);
readable.pipe(res);
} else {
res.end();
}
}
Thanks
URLs
No response
Additional information
- [ ] Would you be willing to help?
URLs
No response
Additional information
- [ ] Would you be willing to help?