mirror of
https://github.com/kevin-DL/sapper.git
synced 2026-01-14 12:04:39 +00:00
server-side rendering
This commit is contained in:
@@ -11,13 +11,25 @@ import sourceMapSupport from 'source-map-support';
|
||||
|
||||
sourceMapSupport.install();
|
||||
|
||||
type RouteObject = {
|
||||
id: string;
|
||||
type: 'page' | 'route';
|
||||
type ServerRoute = {
|
||||
pattern: RegExp;
|
||||
handlers: Record<string, Handler>;
|
||||
params: (match: RegExpMatchArray) => Record<string, string>;
|
||||
module: Component;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
type Page = {
|
||||
pattern: RegExp;
|
||||
parts: Array<{
|
||||
component: Component;
|
||||
params?: (match: RegExpMatchArray) => Record<string, string>;
|
||||
}>
|
||||
};
|
||||
|
||||
type RouteObject = {
|
||||
server_routes: ServerRoute[];
|
||||
pages: Page[];
|
||||
root: Component;
|
||||
error: Component;
|
||||
}
|
||||
|
||||
type Handler = (req: Req, res: ServerResponse, next: () => void) => void;
|
||||
@@ -33,6 +45,7 @@ interface Req extends ClientRequest {
|
||||
method: string;
|
||||
path: string;
|
||||
params: Record<string, string>;
|
||||
query: Record<string, string>;
|
||||
headers: Record<string, string>;
|
||||
}
|
||||
|
||||
@@ -46,7 +59,7 @@ interface Component {
|
||||
}
|
||||
|
||||
export default function middleware({ routes, store }: {
|
||||
routes: RouteObject[],
|
||||
routes: RouteObject,
|
||||
store: (req: Req) => Store
|
||||
}) {
|
||||
const output = locations.dest();
|
||||
@@ -147,8 +160,8 @@ function serve({ prefix, pathname, cache_control }: {
|
||||
};
|
||||
}
|
||||
|
||||
function get_server_route_handler(routes: RouteObject[]) {
|
||||
function handle_route(route, req, res, next) {
|
||||
function get_server_route_handler(routes: ServerRoute[]) {
|
||||
function handle_route(route: ServerRoute, req: Req, res: ServerResponse, next: () => void) {
|
||||
req.params = route.params(route.pattern.exec(req.path));
|
||||
|
||||
const method = req.method.toLowerCase();
|
||||
@@ -210,7 +223,7 @@ function get_server_route_handler(routes: RouteObject[]) {
|
||||
}
|
||||
}
|
||||
|
||||
return function find_route(req: Req, res: ServerResponse, next) {
|
||||
return function find_route(req: Req, res: ServerResponse, next: () => void) {
|
||||
for (const route of routes) {
|
||||
if (route.pattern.test(req.path)) {
|
||||
handle_route(route, req, res, next);
|
||||
@@ -222,7 +235,7 @@ function get_server_route_handler(routes: RouteObject[]) {
|
||||
};
|
||||
}
|
||||
|
||||
function get_page_handler(routes: RouteObject[], store_getter: (req: Req) => Store) {
|
||||
function get_page_handler(routes: RouteObject, store_getter: (req: Req) => Store) {
|
||||
const output = locations.dest();
|
||||
|
||||
const get_chunks = dev()
|
||||
@@ -236,10 +249,11 @@ function get_page_handler(routes: RouteObject[], store_getter: (req: Req) => Sto
|
||||
const { server_routes, pages } = routes;
|
||||
const error_route = routes.error;
|
||||
|
||||
function handle_route(route: RouteObject, req: Req, res: ServerResponse, status = 200, error: Error | string = null) {
|
||||
function handle_page(page: Page, req: Req, res: ServerResponse, status = 200, error: Error | string = null) {
|
||||
const get_params = page.parts[page.parts.length - 1].params || (() => ({}));
|
||||
req.params = error
|
||||
? {}
|
||||
: route.params(route.pattern.exec(req.path));
|
||||
: get_params(page.pattern.exec(req.path));
|
||||
|
||||
const chunks: Record<string, string> = get_chunks();
|
||||
|
||||
@@ -248,7 +262,8 @@ function get_page_handler(routes: RouteObject[], store_getter: (req: Req) => Sto
|
||||
// preload main.js and current route
|
||||
// TODO detect other stuff we can preload? images, CSS, fonts?
|
||||
const link = []
|
||||
.concat(chunks.main, chunks[route.id] || chunks._error) // TODO this is gross
|
||||
// TODO reinstate this!
|
||||
// .concat(chunks.main, chunks[page.id] || chunks._error) // TODO this is gross
|
||||
.filter(file => !file.match(/\.map$/))
|
||||
.map(file => `<${req.baseUrl}/client/${file}>;rel="preload";as="script"`)
|
||||
.join(', ');
|
||||
@@ -258,61 +273,68 @@ function get_page_handler(routes: RouteObject[], store_getter: (req: Req) => Sto
|
||||
const store = store_getter ? store_getter(req) : null;
|
||||
const props = { params: req.params, query: req.query, path: req.path };
|
||||
|
||||
if (route.error) {
|
||||
props.error = error instanceof Error ? error : { message: error };
|
||||
props.status = status;
|
||||
}
|
||||
// TODO reinstate this!
|
||||
// if (page.error) {
|
||||
// props.error = error instanceof Error ? error : { message: error };
|
||||
// props.status = status;
|
||||
// }
|
||||
|
||||
let redirect: { statusCode: number, location: string };
|
||||
let preload_error: { statusCode: number, message: Error | string };
|
||||
|
||||
Promise.resolve(
|
||||
route.handler.preload ? route.handler.preload.call({
|
||||
redirect: (statusCode: number, location: string) => {
|
||||
redirect = { statusCode, location };
|
||||
},
|
||||
error: (statusCode: number, message: Error | string) => {
|
||||
preload_error = { statusCode, message };
|
||||
},
|
||||
fetch: (url: string, opts?: any) => {
|
||||
const parsed = new URL(url, `http://127.0.0.1:${process.env.PORT}${req.baseUrl ? req.baseUrl + '/' :''}`);
|
||||
|
||||
if (opts) {
|
||||
opts = Object.assign({}, opts);
|
||||
|
||||
const include_cookies = (
|
||||
opts.credentials === 'include' ||
|
||||
opts.credentials === 'same-origin' && parsed.origin === `http://127.0.0.1:${process.env.PORT}`
|
||||
);
|
||||
|
||||
if (include_cookies) {
|
||||
const cookies: Record<string, string> = {};
|
||||
if (!opts.headers) opts.headers = {};
|
||||
|
||||
const str = []
|
||||
.concat(
|
||||
cookie.parse(req.headers.cookie || ''),
|
||||
cookie.parse(opts.headers.cookie || ''),
|
||||
cookie.parse(res.getHeader('Set-Cookie') || '')
|
||||
)
|
||||
.map(cookie => {
|
||||
return Object.keys(cookie)
|
||||
.map(name => `${name}=${encodeURIComponent(cookie[name])}`)
|
||||
.join('; ');
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join(', ');
|
||||
|
||||
opts.headers.cookie = str;
|
||||
Promise.all(page.parts.map(part => {
|
||||
return part.component.preload
|
||||
? part.component.preload.call({
|
||||
redirect: (statusCode: number, location: string) => {
|
||||
if (redirect && redirect.statusCode !== statusCode || redirect.location !== location) {
|
||||
throw new Error(`Conflicting redirects`);
|
||||
}
|
||||
}
|
||||
redirect = { statusCode, location };
|
||||
},
|
||||
error: (statusCode: number, message: Error | string) => {
|
||||
preload_error = { statusCode, message };
|
||||
},
|
||||
fetch: (url: string, opts?: any) => {
|
||||
const parsed = new URL(url, `http://127.0.0.1:${process.env.PORT}${req.baseUrl ? req.baseUrl + '/' :''}`);
|
||||
|
||||
return fetch(parsed.href, opts);
|
||||
},
|
||||
store
|
||||
}, req) : {}
|
||||
).catch(err => {
|
||||
if (opts) {
|
||||
opts = Object.assign({}, opts);
|
||||
|
||||
const include_cookies = (
|
||||
opts.credentials === 'include' ||
|
||||
opts.credentials === 'same-origin' && parsed.origin === `http://127.0.0.1:${process.env.PORT}`
|
||||
);
|
||||
|
||||
if (include_cookies) {
|
||||
const cookies: Record<string, string> = {};
|
||||
if (!opts.headers) opts.headers = {};
|
||||
|
||||
const str = []
|
||||
.concat(
|
||||
cookie.parse(req.headers.cookie || ''),
|
||||
cookie.parse(opts.headers.cookie || ''),
|
||||
cookie.parse(res.getHeader('Set-Cookie') || '')
|
||||
)
|
||||
.map(cookie => {
|
||||
return Object.keys(cookie)
|
||||
.map(name => `${name}=${encodeURIComponent(cookie[name])}`)
|
||||
.join('; ');
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join(', ');
|
||||
|
||||
opts.headers.cookie = str;
|
||||
}
|
||||
}
|
||||
|
||||
return fetch(parsed.href, opts);
|
||||
},
|
||||
store
|
||||
}, req)
|
||||
: {};
|
||||
})).catch(err => {
|
||||
preload_error = { statusCode: 500, message: err };
|
||||
return []; // appease TypeScript
|
||||
}).then(preloaded => {
|
||||
if (redirect) {
|
||||
res.statusCode = redirect.statusCode;
|
||||
@@ -323,20 +345,37 @@ function get_page_handler(routes: RouteObject[], store_getter: (req: Req) => Sto
|
||||
}
|
||||
|
||||
if (preload_error) {
|
||||
handle_route(error_route, req, res, preload_error.statusCode, preload_error.message);
|
||||
// TODO reinstate this!
|
||||
// handle_page(error_route, req, res, preload_error.statusCode, preload_error.message);
|
||||
res.end('oops');
|
||||
return;
|
||||
}
|
||||
|
||||
const serialized = {
|
||||
preloaded: route.handler.preload && try_serialize(preloaded),
|
||||
preloaded: page.parts.map((part, i) => {
|
||||
return part.component.preload && try_serialize(preloaded[i]);
|
||||
}),
|
||||
store: store && try_serialize(store.get())
|
||||
};
|
||||
Object.assign(props, preloaded);
|
||||
|
||||
res.end('TODO');
|
||||
return;
|
||||
const data = Object.assign({}, props, {
|
||||
child: {}
|
||||
});
|
||||
let level = data.child;
|
||||
for (let i = 0; i < page.parts.length; i += 1) {
|
||||
const part = page.parts[i];
|
||||
Object.assign(level, {
|
||||
// TODO segment
|
||||
props: Object.assign({}, props, preloaded[i]),
|
||||
component: part.component
|
||||
});
|
||||
if (i < preloaded.length - 1) {
|
||||
level.props.child = {};
|
||||
}
|
||||
level = level.props.child;
|
||||
}
|
||||
|
||||
const { html, head, css } = App.render({ Page: route.handler, props }, {
|
||||
const { html, head, css } = routes.root.render(data, {
|
||||
store
|
||||
});
|
||||
|
||||
@@ -357,7 +396,7 @@ function get_page_handler(routes: RouteObject[], store_getter: (req: Req) => Sto
|
||||
inline_script += `if ('serviceWorker' in navigator) navigator.serviceWorker.register('${req.baseUrl}/service-worker.js');`;
|
||||
}
|
||||
|
||||
const page = template()
|
||||
const body = template()
|
||||
.replace('%sapper.base%', () => `<base href="${req.baseUrl}/">`)
|
||||
.replace('%sapper.scripts%', () => `<script>${inline_script}</script>${scripts}`)
|
||||
.replace('%sapper.html%', () => html)
|
||||
@@ -365,7 +404,7 @@ function get_page_handler(routes: RouteObject[], store_getter: (req: Req) => Sto
|
||||
.replace('%sapper.styles%', () => (css && css.code ? `<style>${css.code}</style>` : ''));
|
||||
|
||||
res.statusCode = status;
|
||||
res.end(page);
|
||||
res.end(body);
|
||||
|
||||
if (process.send) {
|
||||
process.send({
|
||||
@@ -375,7 +414,7 @@ function get_page_handler(routes: RouteObject[], store_getter: (req: Req) => Sto
|
||||
method: req.method,
|
||||
status: 200,
|
||||
type: 'text/html',
|
||||
body: page
|
||||
body
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -385,13 +424,13 @@ function get_page_handler(routes: RouteObject[], store_getter: (req: Req) => Sto
|
||||
if (!server_routes.some(route => route.pattern.test(req.path))) {
|
||||
for (const page of pages) {
|
||||
if (page.pattern.test(req.path)) {
|
||||
handle_route(page, req, res);
|
||||
handle_page(page, req, res);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
handle_route(error_route, req, res, 404, 'Not found');
|
||||
handle_page(error_route, req, res, 404, 'Not found');
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user