Skip to content

Commit

Permalink
Implement the Astro.request RFC (#2913)
Browse files Browse the repository at this point in the history
* Implement the Astro.request RFC

* Disable console warnings eslint

* Use our logger

* Adds a changeset

* Fix tests that depend on params, canonicalURL, URL

Co-authored-by: Fred K. Schott <[email protected]>
  • Loading branch information
matthewp and FredKSchott authored Mar 29, 2022
1 parent 030fd48 commit ecc6a48
Show file tree
Hide file tree
Showing 34 changed files with 135 additions and 121 deletions.
5 changes: 5 additions & 0 deletions .changeset/perfect-dogs-turn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': minor
---

Implements the Astro.request RFC
2 changes: 1 addition & 1 deletion examples/blog-multiple-authors/src/layouts/post.astro
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Nav from '../components/Nav.astro';
import authorData from '../data/authors.json';
const { content } = Astro.props;
let canonicalURL = Astro.request.canonicalURL;
let canonicalURL = Astro.canonicalURL;
---

<html lang={content.lang || 'en'}>
Expand Down
2 changes: 1 addition & 1 deletion examples/blog-multiple-authors/src/pages/about.astro
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Nav from '../components/Nav.astro';
let title = 'About';
let description = 'About page of an example blog on Astro';
let canonicalURL = Astro.request.canonicalURL;
let canonicalURL = Astro.canonicalURL;
---

<html lang="en">
Expand Down
2 changes: 1 addition & 1 deletion examples/blog-multiple-authors/src/pages/index.astro
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import authorData from '../data/authors.json';
// All variables are available to use in the HTML template below.
let title = 'Don’s Blog';
let description = 'An example blog on Astro';
let canonicalURL = Astro.request.canonicalURL;
let canonicalURL = Astro.canonicalURL;
// Data Fetching: List all Markdown posts in the repo.
let allPosts = await Astro.glob('./post/*.md');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ export async function getStaticPaths({ paginate, rss }) {
}
// page
let title = 'Don’s Blog';
let description = 'An example blog on Astro';
let canonicalURL = Astro.request.canonicalURL;
const title = 'Don’s Blog';
const description = 'An example blog on Astro';
const { canonicalURL } = Astro;
const { page } = Astro.props;
---

Expand Down
2 changes: 1 addition & 1 deletion examples/docs/src/layouts/MainLayout.astro
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const githubEditUrl = CONFIG.GITHUB_EDIT_URL && CONFIG.GITHUB_EDIT_URL + current
<html dir={content.dir ?? 'ltr'} lang={content.lang ?? 'en-us'} class="initial">
<head>
<HeadCommon />
<HeadSEO {content} canonicalURL={Astro.request.canonicalURL} />
<HeadSEO {content} canonicalURL={Astro.canonicalURL} />
<title>{content.title ? `${content.title} 🚀 ${CONFIG.SITE.title}` : CONFIG.SITE.title}</title>
<style>
body {
Expand Down
2 changes: 1 addition & 1 deletion examples/ssr/src/pages/products/[id].astro
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import AddToCart from '../../components/AddToCart.svelte';
import { getProduct } from '../../api';
import '../../styles/common.css';
const id = Number(Astro.request.params.id);
const id = Number(Astro.params.id);
const product = await getProduct(id);
---

Expand Down
9 changes: 6 additions & 3 deletions packages/astro/src/@types/astro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import type * as vite from 'vite';
import { z } from 'zod';
import type { AstroConfigSchema } from '../core/config';
import type { AstroComponentFactory, Metadata } from '../runtime/server';
import type { AstroRequest } from '../core/render/request';
export type { SSRManifest } from '../core/app/types';

export interface AstroBuiltinProps {
Expand Down Expand Up @@ -51,10 +50,14 @@ export interface BuildConfig {
* Docs: https://docs.astro.build/reference/api-reference/#astro-global
*/
export interface AstroGlobal extends AstroGlobalPartial {
/** get the current canonical URL */
canonicalURL: URL;
/** get page params (dynamic pages only) */
params: Params;
/** set props for this astro component (along with default values) */
props: Record<string, number | string | any>;
/** get information about this page */
request: AstroRequest;
request: Request;
/** see if slots are used */
slots: Record<string, true | undefined> & { has(slotName: string): boolean; render(slotName: string): Promise<string> };
}
Expand Down Expand Up @@ -632,7 +635,7 @@ export interface EndpointOutput<Output extends Body = Body> {
}

export interface EndpointHandler {
[method: string]: (params: any, request: AstroRequest) => EndpointOutput | Response;
[method: string]: (params: any, request: Request) => EndpointOutput | Response;
}

export interface AstroRenderer {
Expand Down
12 changes: 6 additions & 6 deletions packages/astro/src/core/app/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,15 @@ import { call as callEndpoint } from '../endpoint/index.js';
import { RouteCache } from '../render/route-cache.js';
import { createLinkStylesheetElementSet, createModuleScriptElementWithSrcSet } from '../render/ssr-element.js';
import { prependForwardSlash } from '../path.js';
import { createRequest } from '../request.js';

export class App {
#manifest: Manifest;
#manifestData: ManifestData;
#routeDataToRouteInfo: Map<RouteData, RouteInfo>;
#routeCache: RouteCache;
#encoder = new TextEncoder();
#logging = defaultLogOptions;

constructor(manifest: Manifest) {
this.#manifest = manifest;
Expand Down Expand Up @@ -63,7 +65,7 @@ export class App {
const result = await render({
legacyBuild: false,
links,
logging: defaultLogOptions,
logging: this.#logging,
markdownRender: manifest.markdown.render,
mod,
origin: url.origin,
Expand All @@ -81,8 +83,7 @@ export class App {
routeCache: this.#routeCache,
site: this.#manifest.site,
ssr: true,
method: info.routeData.type === 'endpoint' ? '' : 'GET',
headers: request.headers,
request,
});

if (result.type === 'response') {
Expand All @@ -100,15 +101,14 @@ export class App {
});
}

async #callEndpoint(request: Request, routeData: RouteData, mod: ComponentInstance): Promise<Response> {
async #callEndpoint(request: Request, _routeData: RouteData, mod: ComponentInstance): Promise<Response> {
const url = new URL(request.url);
const handler = mod as unknown as EndpointHandler;
const result = await callEndpoint(handler, {
headers: request.headers,
logging: defaultLogOptions,
method: request.method,
origin: url.origin,
pathname: url.pathname,
request,
routeCache: this.#routeCache,
ssr: true,
});
Expand Down
5 changes: 3 additions & 2 deletions packages/astro/src/core/build/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { getOutFile, getOutFolder } from './common.js';
import { eachPageData, getPageDataByComponent } from './internal.js';
import type { PageBuildData, SingleFileBuiltModule, StaticBuildOptions } from './types';
import { getTimeStat } from './util.js';
import { createRequest } from '../request.js';

// Render is usually compute, which Node.js can't parallelize well.
// In real world testing, dropping from 10->1 showed a notiable perf
Expand Down Expand Up @@ -164,6 +165,7 @@ async function generatePath(pathname: string, opts: StaticBuildOptions, gopts: G
}
}

const url = new URL(origin + pathname);
const options: RenderOptions = {
legacyBuild: false,
links,
Expand Down Expand Up @@ -191,8 +193,7 @@ async function generatePath(pathname: string, opts: StaticBuildOptions, gopts: G
const fullyRelativePath = relPath[0] === '.' ? relPath : './' + relPath;
return fullyRelativePath;
},
method: 'GET',
headers: new Headers(),
request: createRequest({ url, headers: new Headers(), logging }),
route: pageData.route,
routeCache,
site: astroConfig.buildOptions.site,
Expand Down
7 changes: 3 additions & 4 deletions packages/astro/src/core/endpoint/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import type { EndpointHandler } from '../../@types/astro';
import type { RenderOptions } from '../render/core';
import { renderEndpoint } from '../../runtime/server/index.js';
import { getParamsAndProps, GetParamsAndPropsError } from '../render/core.js';
import { createRequest } from '../render/request.js';

export type EndpointOptions = Pick<RenderOptions, 'logging' | 'headers' | 'method' | 'origin' | 'route' | 'routeCache' | 'pathname' | 'route' | 'site' | 'ssr'>;
export type EndpointOptions = Pick<RenderOptions, 'logging' | 'origin' |
'request' | 'route' | 'routeCache' | 'pathname' | 'route' | 'site' | 'ssr'>;

type EndpointCallResult =
| {
Expand All @@ -23,9 +23,8 @@ export async function call(mod: EndpointHandler, opts: EndpointOptions): Promise
throw new Error(`[getStaticPath] route pattern matched, but no matching static path found. (${opts.pathname})`);
}
const [params] = paramsAndPropsResp;
const request = createRequest(opts.method, opts.pathname, opts.headers, opts.origin, opts.site, opts.ssr);

const response = await renderEndpoint(mod, request, params);
const response = await renderEndpoint(mod, opts.request, params);

if (response instanceof Response) {
return {
Expand Down
9 changes: 3 additions & 6 deletions packages/astro/src/core/render/core.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import type { ComponentInstance, EndpointHandler, MarkdownRenderOptions, Params, Props, SSRLoadedRenderer, RouteData, SSRElement } from '../../@types/astro';
import type { LogOptions } from '../logger.js';
import type { AstroRequest } from './request';

import { renderHead, renderPage } from '../../runtime/server/index.js';
import { getParams } from '../routing/index.js';
Expand Down Expand Up @@ -71,12 +70,11 @@ export interface RenderOptions {
routeCache: RouteCache;
site?: string;
ssr: boolean;
method: string;
headers: Headers;
request: Request;
}

export async function render(opts: RenderOptions): Promise<{ type: 'html'; html: string } | { type: 'response'; response: Response }> {
const { headers, legacyBuild, links, logging, origin, markdownRender, method, mod, pathname, scripts, renderers, resolve, route, routeCache, site, ssr } = opts;
const { legacyBuild, links, logging, origin, markdownRender, mod, pathname, scripts, renderers, request, resolve, route, routeCache, site, ssr } = opts;

const paramsAndPropsRes = await getParamsAndProps({
logging,
Expand Down Expand Up @@ -107,11 +105,10 @@ export async function render(opts: RenderOptions): Promise<{ type: 'html'; html:
pathname,
resolve,
renderers,
request,
site,
scripts,
ssr,
method,
headers,
});

let page = await renderPage(result, Component, pageProps, null);
Expand Down
11 changes: 4 additions & 7 deletions packages/astro/src/core/render/dev/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,8 @@ export interface SSROptions {
routeCache: RouteCache;
/** Vite instance */
viteServer: vite.ViteDevServer;
/** Method */
method: string;
/** Headers */
headers: Headers;
/** Request */
request: Request;
}

export type ComponentPreload = [SSRLoadedRenderer[], ComponentInstance];
Expand Down Expand Up @@ -64,7 +62,7 @@ export async function preload({ astroConfig, filePath, viteServer }: Pick<SSROpt

/** use Vite to SSR */
export async function render(renderers: SSRLoadedRenderer[], mod: ComponentInstance, ssrOpts: SSROptions): Promise<RenderResponse> {
const { astroConfig, filePath, logging, mode, origin, pathname, method, headers, route, routeCache, viteServer } = ssrOpts;
const { astroConfig, filePath, logging, mode, origin, pathname, request, route, routeCache, viteServer } = ssrOpts;
const legacy = astroConfig.buildOptions.legacyBuild;

// Add hoisted script tags
Expand Down Expand Up @@ -144,12 +142,11 @@ export async function render(renderers: SSRLoadedRenderer[], mod: ComponentInsta
}
},
renderers,
request,
route,
routeCache,
site: astroConfig.buildOptions.site,
ssr: astroConfig.buildOptions.experimentalSsr,
method,
headers,
});

if (route?.type === 'endpoint' || content.type === 'response') {
Expand Down
50 changes: 0 additions & 50 deletions packages/astro/src/core/render/request.ts

This file was deleted.

13 changes: 7 additions & 6 deletions packages/astro/src/core/render/result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { AstroGlobal, AstroGlobalPartial, MarkdownParser, MarkdownRenderOpt
import { renderSlot } from '../../runtime/server/index.js';
import { LogOptions, warn } from '../logger.js';
import { isCSSRequest } from './dev/css.js';
import { createRequest } from './request.js';
import { canonicalURL as utilCanonicalURL } from '../util.js';
import { isScriptRequest } from './script.js';

function onlyAvailableInSSR(name: string) {
Expand All @@ -26,8 +26,7 @@ export interface CreateResultArgs {
site: string | undefined;
links?: Set<SSRElement>;
scripts?: Set<SSRElement>;
headers: Headers;
method: string;
request: Request;
}

class Slots {
Expand Down Expand Up @@ -72,10 +71,10 @@ class Slots {
}

export function createResult(args: CreateResultArgs): SSRResult {
const { legacyBuild, markdownRender, method, origin, headers, params, pathname, renderers, resolve, site } = args;
const { legacyBuild, markdownRender, origin, params, pathname, renderers, request, resolve, site } = args;

const request = createRequest(method, pathname, headers, origin, site, args.ssr);
request.params = params;
const url = new URL(request.url);
const canonicalURL = utilCanonicalURL('.' + pathname, site ?? url.origin);

// Create the result object that will be passed into the render function.
// This object starts here as an empty shell (not yet the result) but then
Expand All @@ -90,6 +89,8 @@ export function createResult(args: CreateResultArgs): SSRResult {

const Astro = {
__proto__: astroGlobal,
canonicalURL,
params,
props,
request,
redirect: args.ssr
Expand Down
Loading

0 comments on commit ecc6a48

Please sign in to comment.