summaryrefslogtreecommitdiff
path: root/packages/integrations/netlify/src/netlify-functions.ts
blob: c0881bb05e8399b232ef8584ed42fd070af8e41d (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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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 {}

export const createExports = (manifest: SSRManifest, args: Args) => {
	const app = new App(manifest);

	const handler: Handler = async (event) => {
		const { httpMethod, headers, rawUrl, body: requestBody, isBase64Encoded } = event;
		const init: RequestInit = {
			method: httpMethod,
			headers: new Headers(headers as any),
		};
		// Attach the event body the the request, with proper encoding.
		if (httpMethod !== 'GET' && httpMethod !== 'HEAD') {
			const encoding = isBase64Encoded ? 'base64' : 'utf-8';
			init.body =
				typeof requestBody === 'string' ? Buffer.from(requestBody, encoding) : requestBody;
		}
		const request = new Request(rawUrl, init);

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

		const response: Response = await app.render(request);
		const responseBody = await response.text();

		const responseHeaders = Object.fromEntries(response.headers.entries());
		const fnResponse: any = {
			statusCode: response.status,
			headers: responseHeaders,
			body: responseBody,
		};

		// Special-case set-cookie which has to be set an different way :/
		// The fetch API does not have a way to get multiples of a single header, but instead concatenates
		// them. There are non-standard ways to do it, and node-fetch gives us headers.raw()
		// See https://github.com/whatwg/fetch/issues/973 for discussion
		if (response.headers.has('set-cookie') && 'raw' in response.headers) {
			// Node fetch allows you to get the raw headers, which includes multiples of the same type.
			// This is needed because Set-Cookie *must* be called for each cookie, and can't be
			// concatenated together.
			type HeadersWithRaw = Headers & {
				raw: () => Record<string, string[]>;
			};

			const rawPacked = (response.headers as HeadersWithRaw).raw();
			if ('set-cookie' in rawPacked) {
				fnResponse.multiValueHeaders = {
					'set-cookie': rawPacked['set-cookie'],
				};
			}
		}

		return fnResponse;
	};

	return { handler };
};