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

Always return something from render #847

Merged
merged 5 commits into from
Apr 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/quiet-mangos-shop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

Always return a response from render function in handle
2 changes: 1 addition & 1 deletion documentation/docs/04-hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ type Response = {

type Handle<Context = any> = (
request: Request<Context>,
render: (request: Request<Context>) => Response | Promise<Response>
render: (request: Request<Context>) => Promise<Response>
) => Response | Promise<Response>;
```

Expand Down
43 changes: 21 additions & 22 deletions packages/kit/src/core/adapt/prerender.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,9 @@ export async function prerender({ cwd, out, log, config, force }) {
if (seen.has(path)) return;
seen.add(path);

/** @type {Map<string, import('types').Response>} */
const dependencies = new Map();

const rendered = await app.render(
{
host: config.kit.host,
Expand All @@ -95,6 +98,7 @@ export async function prerender({ cwd, out, log, config, force }) {
},
{
local: true,
dependencies,
only_render_prerenderable_pages: !force,
get_static_file: (file) => readFileSync(join(config.kit.files.assets, file))
}
Expand Down Expand Up @@ -123,39 +127,34 @@ export async function prerender({ cwd, out, log, config, force }) {
return;
}

if (response_type === OK) {
if (rendered.status === 200) {
log.info(`${rendered.status} ${path}`);
writeFileSync(file, rendered.body); // TODO minify where possible?
} else {
} else if (response_type !== OK) {
error(rendered.status, path);
}

const { dependencies } = rendered;

if (dependencies) {
for (const path in dependencies) {
const result = dependencies[path];
const response_type = Math.floor(result.status / 100);
dependencies.forEach((result, path) => {
const response_type = Math.floor(result.status / 100);

const is_html = result.headers['content-type'] === 'text/html';
const is_html = result.headers['content-type'] === 'text/html';

const parts = path.split('/');
if (is_html && parts[parts.length - 1] !== 'index.html') {
parts.push('index.html');
}
const parts = path.split('/');
if (is_html && parts[parts.length - 1] !== 'index.html') {
parts.push('index.html');
}

const file = `${out}${parts.join('/')}`;
mkdirp(dirname(file));
const file = `${out}${parts.join('/')}`;
mkdirp(dirname(file));

writeFileSync(file, result.body);
writeFileSync(file, result.body);

if (response_type === OK) {
log.info(`${result.status} ${path}`);
} else {
error(result.status, path);
}
if (response_type === OK) {
log.info(`${result.status} ${path}`);
} else {
error(result.status, path);
}
}
});

if (is_html && config.kit.prerender.crawl) {
const cleaned = clean_html(rendered.body);
Expand Down
2 changes: 2 additions & 0 deletions packages/kit/src/core/build/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,7 @@ async function build_server(
export function render(request, {
paths = ${s(config.kit.paths)},
local = false,
dependencies,
only_render_prerenderable_pages = false,
get_static_file
} = {}) {
Expand All @@ -371,6 +372,7 @@ async function build_server(
hooks,
dev: false,
amp: ${config.kit.amp},
dependencies,
only_render_prerenderable_pages,
app_dir: ${s(config.kit.appDir)},
get_component_path: id => ${s(`${config.kit.paths.assets}/${config.kit.appDir}/`)} + client_component_lookup[id],
Expand Down
2 changes: 1 addition & 1 deletion packages/kit/src/runtime/server/endpoint.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* @param {import('types').Request} request
* @param {import('types.internal').SSREndpoint} route
* @returns {Promise<import('types.internal').ResponseWithDependencies>}
* @returns {Promise<import('types').Response>}
*/
export default async function render_route(request, route) {
const mod = await route.load();
Expand Down
32 changes: 20 additions & 12 deletions packages/kit/src/runtime/server/page.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,9 @@ const s = JSON.stringify;
* status: number;
* error: Error
* }} opts
* @returns {Promise<import('types.internal').ResponseWithDependencies>}
* @returns {Promise<import('types').Response>}
*/
async function get_response({ request, options, $session, route, status = 200, error }) {
/** @type {Record<string, import('types.internal').ResponseWithDependencies>} */
const dependencies = {};

const serialized_session = try_serialize($session, (error) => {
throw new Error(`Failed to serialize session data: ${error.message}`);
});
Expand Down Expand Up @@ -146,9 +143,9 @@ async function get_response({ request, options, $session, route, status = 200, e
);

if (rendered) {
// TODO this is primarily for the benefit of the static case,
// but could it be used elsewhere?
dependencies[resolved] = rendered;
if (options.dependencies) {
options.dependencies.set(resolved, rendered);
}

response = new Response(rendered.body, {
status: rendered.status,
Expand Down Expand Up @@ -240,11 +237,23 @@ async function get_response({ request, options, $session, route, status = 200, e
};

if (options.only_render_prerenderable_pages) {
if (error) return; // don't prerender an error page
if (error) {
return {
status,
headers: {},
body: error.message
};
}

// if the page has `export const prerender = true`, continue,
// otherwise bail out at this point
if (!page_component.prerender) return;
if (!page_component.prerender) {
return {
status: 204,
headers: {},
body: null
};
}
}

/** @type {{ head: string, html: string, css: string }} */
Expand Down Expand Up @@ -468,16 +477,15 @@ async function get_response({ request, options, $session, route, status = 200, e
return {
status,
headers,
body: options.template({ head, body }),
dependencies
body: options.template({ head, body })
};
}

/**
* @param {import('types').Request} request
* @param {import('types.internal').SSRPage} route
* @param {import('types.internal').SSRRenderOptions} options
* @returns {Promise<import('types.internal').ResponseWithDependencies>}
* @returns {Promise<import('types').Response>}
*/
export default async function render_page(request, route, options) {
if (options.initiator === route) {
Expand Down
7 changes: 2 additions & 5 deletions packages/kit/types.internal.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export type App = {
};
prerendering: boolean;
}) => void;
render: (incoming: Incoming, options: SSRRenderOptions) => ResponseWithDependencies;
render: (incoming: Incoming, options: SSRRenderOptions) => Response;
};

// TODO we want to differentiate between request headers, which
Expand All @@ -74,10 +74,6 @@ export type App = {
// but this can't happen until TypeScript 4.3
export type Headers = Record<string, string>;

export type ResponseWithDependencies = Response & {
dependencies?: Record<string, Response>;
};

export type Page = {
host: string;
path: string;
Expand Down Expand Up @@ -185,6 +181,7 @@ export type SSRRenderOptions = {
hooks?: Hooks;
dev?: boolean;
amp?: boolean;
dependencies?: Map<string, Response>;
only_render_prerenderable_pages?: boolean;
app_dir?: string;
get_component_path?: (id: string) => string;
Expand Down