forked from smooth80/bouncer.js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
64 lines (54 loc) · 1.47 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
'use strict'
// dependencies
const Cache = require('latermom')
const BouncerJs = require('.')
const fileReader = require('./lib/file-reader')
/**
* static files server, returning bouncer instance
* @param {string?} dist
* @param {object?} plugins
* @param {object?} config
* @returns BouncerJS
*/
function server(
// first argument is directory you want to static serve
dist = 'dist',
// second argument is plugins object with functions - more in README.md
plugins = {},
// extra configuration for bouncer
config = {}
) {
// get bouncer from second argument
const bouncer =
arguments.length === 2
? arguments[1]
: new BouncerJs({ ...config, plugins })
// init cache with fileReader on dist folder
const cache = new Cache(fileReader(dist))
// process all requests
bouncer.router.get('/*', (res, req) => {
const url = req.getUrl()
const { mime, body, status } = cache.get(url)
if (bouncer.config.debug) {
console.info(status, 'GET', mime, url)
}
// send 200 for google seo
res.writeStatus('200 OK')
// check based on real status from file-reader
switch (status) {
case 301:
const index = cache.get('/index.html')
res.writeHeader('Content-Type', index.mime)
res.end(index.body)
break
default:
res.writeHeader('Content-Type', mime)
res.end(body)
break
}
})
// return bouncer.js instance
return bouncer
}
// export
module.exports = server