summaryrefslogtreecommitdiff
path: root/packages/integrations/netlify/src/netlify-functions.ts
blob: cf6c871a9b6869f9b878b65dfeec9cb4105b7661 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { SSRManifest } from 'astro';
import type { Handler } from "@netlify/functions";
import { App } from 'astro/app';
import { polyfill } from '@astrojs/webapi';

polyfill(globalThis, {
	exclude: 'window document',
});

interface Args {
	site?: string;
}

export const createExports = (manifest: SSRManifest, args: Args) => {
	const app = new App(manifest);
	const site = new URL(args.site ?? `https://netlify.com`);

	const handler: Handler = async (event) => {
		const headers = new Headers(event.headers as any);
		const request = new Request(new URL(event.path, site).toString(), {
			method: event.httpMethod,
			headers
		});

		if(!app.match(request)) {
			return {
				statusCode: 404,
				body: 'Not found'
			};
		}

		const response = await app.render(request);
		const body = await response.text();

		return {
			statusCode: 200,
			headers: Object.fromEntries(response.headers.entries()),
			body
		};
	}

	return { handler };
};