-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfastify-svelte.js
46 lines (33 loc) · 1.15 KB
/
fastify-svelte.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
import fp from 'fastify-plugin'
import {join} from 'path'
const assetUrlConstructor = () => (page, type) => {
return `/views/templates/${page}.${type}`;
};
const defaultOptions = {
assetUrlConstructor: assetUrlConstructor,
svelteTemplatesPath: '../views/templates'
};
export default fp((fastify, options, next) =>{
const {
assetUrlConstructor,
svelteTemplatesPath,
} = {...defaultOptions, ...options};
const assetUrl = assetUrlConstructor(fastify);
const loadTemplate = page => import(`${svelteTemplatesPath}/${page}.js`).then(module => module.default);
fastify.decorateReply('view', async function (page, props){
const reply = this;
const view = await loadTemplate(page);
const { html, head } = view.render(props);
const render = await loadTemplate('base')
const replaces = {
content: html,
css: assetUrl(page, 'css'),
head,
props: JSON.stringify(props),
script: assetUrl(page, 'js'),
};
const rendered = render(replaces);
reply.type('text/html').send(rendered);
});
next();
});