-
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathhandler.js
76 lines (65 loc) · 1.75 KB
/
handler.js
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
71
72
73
74
75
76
import './shims';
import { App } from 'APP';
/**
* @param {import('@sveltejs/kit').SSRManifest} manifest
* @returns {import('@netlify/functions').Handler}
*/
export function init(manifest) {
const app = new App(manifest);
return async (event) => {
const { httpMethod, headers, rawUrl, body, isBase64Encoded } = event;
const encoding = isBase64Encoded ? 'base64' : 'utf-8';
const rawBody = typeof body === 'string' ? Buffer.from(body, encoding) : body;
const rendered = await app.render(
new Request(rawUrl, {
method: httpMethod,
headers: new Headers(headers),
body: rawBody
})
);
const partial_response = {
statusCode: rendered.status,
...split_headers(rendered.headers)
};
// TODO this is probably wrong now?
if (rendered.body instanceof Uint8Array) {
// Function responses should be strings (or undefined), and responses with binary
// content should be base64 encoded and set isBase64Encoded to true.
// /~https://github.com/netlify/functions/blob/main/src/function/response.ts
return {
...partial_response,
isBase64Encoded: true,
body: Buffer.from(rendered.body).toString('base64')
};
}
return {
...partial_response,
body: await rendered.text()
};
};
}
/**
* Splits headers into two categories: single value and multi value
* @param {Headers} headers
* @returns {{
* headers: Record<string, string>,
* multiValueHeaders: Record<string, string[]>
* }}
*/
function split_headers(headers) {
/** @type {Record<string, string>} */
const h = {};
/** @type {Record<string, string[]>} */
const m = {};
headers.forEach((value, key) => {
if (key === 'set-cookie') {
m[key] = value.split(', ');
} else {
h[key] = value;
}
});
return {
headers: h,
multiValueHeaders: m
};
}