diff --git a/packages/core/package.json b/packages/core/package.json index 5b16db3..8761c0a 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "swtl", - "version": "0.3.4", + "version": "0.3.5", "description": "", "main": "index.js", "type": "module", diff --git a/packages/core/router.js b/packages/core/router.js index 1ed3e62..69a76ad 100644 --- a/packages/core/router.js +++ b/packages/core/router.js @@ -14,7 +14,7 @@ export class Router { /** * @param {{ * routes: Route[], - * fallback: (args: RouteArgs) => RouteResult, + * fallback?: (args: RouteArgs) => RouteResult, * plugins?: Plugin[], * baseHref?: string, * customElementRenderers?: CustomElementRenderer[] @@ -58,6 +58,7 @@ export class Router { /** * @param {Request} request + * @returns {Promise} */ async handleRequest(request) { const url = new URL(request.url); @@ -96,7 +97,7 @@ export class Router { } } - return new HtmlResponse( + return createResponse( await route({url, query, params, request}), matchedRoute?.options ?? {}, { @@ -107,43 +108,50 @@ export class Router { } } +/** + * @param {*} template + * @param {*} routeOptions + * @param {*} renderOptions + * @returns + */ +function createResponse(template, routeOptions, renderOptions) { + const iterator = render(template, renderOptions.renderers); + const encoder = new TextEncoder(); + const stream = new ReadableStream({ + async pull(controller) { + try { + const { value, done } = await iterator.next(); + + if (done) { + controller.close(); + } else { + controller.enqueue(encoder.encode(value)); + } + } catch(e) { + console.error(/** @type {Error} */ (e).stack); + throw e; + } + } + }); + + return new Response(stream, { + status: 200, + headers: { + 'Content-Type': 'text/html', + 'Transfer-Encoding': 'chunked', + ...(routeOptions?.headers ?? {}) + }, + ...routeOptions + }); +} + export class HtmlResponse { /** - * * @param {unknown} template * @param {*} routeOptions * @param {*} renderOptions - * @returns */ constructor(template, routeOptions = {}, renderOptions = {}) { - // @ts-expect-error - const iterator = render(template, renderOptions.renderers); - const encoder = new TextEncoder(); - const stream = new ReadableStream({ - async pull(controller) { - try { - const { value, done } = await iterator.next(); - - if (done) { - controller.close(); - } else { - controller.enqueue(encoder.encode(value)); - } - } catch(e) { - console.error(/** @type {Error} */ (e).stack); - throw e; - } - } - }); - - return new Response(stream, { - status: 200, - headers: { - 'Content-Type': 'text/html', - 'Transfer-Encoding': 'chunked', - ...(routeOptions?.headers ?? {}) - }, - ...routeOptions - }); + return createResponse(template, routeOptions, renderOptions); } } \ No newline at end of file