-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
52 lines (46 loc) · 1.26 KB
/
index.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
const htm = require('./dependencies/htm');
const vhtml = require('./dependencies/vhtml');
const buildCacheHeader = require('./utils/caching');
const html = htm.bind(vhtml);
const defaults = {
Layout: ({ children, scripts = [], styles = []}) => html`
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1" />
${styles.map(stylesheet => html`<link rel="stylesheet" href=${stylesheet} />`)}
</head>
<body>
${scripts.map(script => html`<script src=${script} async></script>`)}
${children}
</body>
</html>`,
}
function view(fn, options = {}) {
return async function handler(event, context) {
const Layout = options.Layout || defaults.Layout;
try {
const result = await fn(event, context);
return {
statusCode: 200,
headers: {
'cache-control': buildCacheHeader(options.caching),
'content-type': 'text/html; charset=utf-8'
},
body: `<!DOCTYPE html>${html`<${Layout}
scripts=${options.scripts}
styles=${options.styles}
>${result}<//>`}`
}
} catch(e) {
return {
statusCode: 500,
headers: {
'cache-control': buildCacheHeader(),
'content-type': 'text/html; charset=utf-8'
},
body: `<!DOCTYPE html>${html`<${Layout}>${e.message}<//>`}`
}
}
}
}
module.exports = { html, view };