UNPKG

@curveball/core

Version:

Curveball is a framework writting in Typescript for Node.js

77 lines 2.51 kB
import { Readable } from 'node:stream'; import { NodeRequest as CurveballNodeRequest } from './request.js'; import { NodeResponse as CurveballNodeResponse } from './response.js'; import { isHttpError } from '@curveball/http-errors'; import { Context, } from '@curveball/kernel'; /** * A type guard to see if a Response object is a HTTP2 response. */ export function isHttp2Response(response) { return response.stream !== undefined; } /** * Returns a callback that can be used with Node's http.Server, http2.Server, https.Server. * * Normally you want to pass this to the constructor of each of these classes. */ export function nodeHttpServerCallback(app) { return async (req, res) => { try { const ctx = createContextFromNode(req, res, app.origin); await app.handle(ctx); sendBody(res, ctx.response.body); } catch (err) { // eslint-disable-next-line no-console console.error(err); if (isHttpError(err)) { res.statusCode = err.httpStatus; } else { res.statusCode = 500; } res.setHeader('Content-Type', 'text/plain'); res.end('Uncaught exception. No middleware was defined to handle it. We got the following HTTP status: ' + res.statusCode); if (app.listenerCount('error')) { app.emit('error', err); } } }; } /** * Emits a 'body' from a Curveball response to a Node HTTP stream/socket */ export function sendBody(res, body) { if (body === null) { res.end(); return; } else if (typeof body === 'string') { res.end(body); } else if (body instanceof Buffer) { res.end(body); } else if (body instanceof Readable) { body.pipe(res); } else if (typeof body === 'object') { res.end(JSON.stringify(body, null, 2)); } else if (typeof body === 'function') { body(res); } else { throw new TypeError('Unsupported type for body: ' + typeof body); } } /** * This function takes the request and response objects from a Node http, * https or http2 server and returns a curveball compatible Context. */ export function createContextFromNode(req, res, origin) { const context = new Context(new CurveballNodeRequest(req, origin), new CurveballNodeResponse(res, origin)); return context; } //# sourceMappingURL=http-utils.js.map