UNPKG

@fanoutio/grip

Version:
40 lines (39 loc) 1.4 kB
import { getWebSocketContextImpl, isWsOverHttpImpl } from '../../utilities/index.js'; function headersFromNodeIncomingHttpHeaders(incomingHttpHeaders) { const headers = new Headers(); for (const [key, value] of Object.entries(incomingHttpHeaders)) { if (value == null) { continue; } if (!Array.isArray(value)) { headers.append(key, value); continue; } // Should only be for set-cookie // https://nodejs.org/api/http.html#messageheaders for (const entry of value) { headers.append(key, entry); } } return headers; } export function isNodeReqWsOverHttp(req) { return isWsOverHttpImpl(req.method, headersFromNodeIncomingHttpHeaders(req.headers)); } export async function getWebSocketContextFromNodeReq(req, prefix = '') { return getWebSocketContextImpl(headersFromNodeIncomingHttpHeaders(req.headers), async () => { return new Promise(resolve => { const bodyParts = []; req.on('data', (chunk) => { if (typeof chunk === 'string') { chunk = Buffer.from(chunk); } bodyParts.push(chunk); }); req.on('end', () => { const body = Buffer.concat(bodyParts); resolve(body); }); }); }, prefix); }