-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
115 lines (67 loc) · 1.91 KB
/
server.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import chokidar from 'chokidar';
import decache from 'decache';
import express from 'express';
import dotenv from 'dotenv/config';
import fs from 'fs';
import cache from './cache.js';
import createPage from './createPage';
import edgeConfig from './edge.config.js';
const app = express();
app.use( express.static( 'public' ) );
//
// Routes.
if( !! edgeConfig.routes && !! edgeConfig.routes.length ) {
for( let { src, dest } of edgeConfig.routes ) {
app.get( src, async ( req, res ) => {
const templateFile = `.${dest}${! dest.includes( 'js' ) ? '.js' : '' }`;
import( templateFile )
.then( async ( { default: component } ) => {
const page = await createPage( {
templateFile,
component,
} );
res.send( page );
} );
} );
}
app.get( '/test', ( req, res ) => {
cache.set( 'currentTemplate', 'test' );
cache.set( 'html', 'test' );
res.send('test');
} );
// SSE.
app.get( '/__watch', ( req, res ) => {
if( ! req.query || ! req.query.template ) {
return;
}
const templateFile = req.query.template;
res.status( 200 ).set( {
'connection': 'keep-alive',
'cache-control': 'no-cache',
'content-type': 'text/event-stream',
} );
// Watch.
const watcher = chokidar.watch( '.', {
ignored: [ 'node_modules', '.edge' ],
} )
.on( 'change', path => {
const oldHTML = cache.get( 'html' );
if( ! oldHTML ) {
return;
}
import( templateFile )
.then( async ( { default: component } ) => {
const newHTML = await createPage( {
templateFile,
component
} );
if( oldHTML == newHTML ) {
return;
}
console.log( 'Sending updated html' );
res.write( `data: ${JSON.stringify( { newHTML } ) }\n\n` );
} );
} );
} );
}
app.listen( 3000 );