1 | 'use strict'
|
2 |
|
3 | const path = require('path')
|
4 | const mm = require('micromatch')
|
5 | const mime = require('mime')
|
6 | const rename = require('rename-extension')
|
7 | const log = require('./log')
|
8 | const cache = require('./cache')
|
9 | const execute = require('./execute')
|
10 | const send = require('./send')
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 | module.exports = function(routes, srcPath) {
|
20 |
|
21 | return (req, res, next) => {
|
22 |
|
23 |
|
24 | const fileRoute = req.url.substr(1).split('?')[0]
|
25 |
|
26 |
|
27 | const matches = routes.filter((route) => mm.isMatch(fileRoute, route.path))
|
28 | const route = matches[0]
|
29 |
|
30 |
|
31 | if (route==null) return next()
|
32 |
|
33 |
|
34 | if (cache.get(fileRoute)!=null) {
|
35 |
|
36 | log(`{cyan:Using cached handler: {magenta:${ route.name } {grey:${ fileRoute }`)
|
37 |
|
38 | const cachedHandler = cache.get(fileRoute)
|
39 |
|
40 |
|
41 | return send(res, cachedHandler.contentType, cachedHandler.data)
|
42 |
|
43 | }
|
44 |
|
45 |
|
46 | const filePath = path.join(srcPath, fileRoute)
|
47 |
|
48 |
|
49 | const fileLoad = (() => {
|
50 |
|
51 |
|
52 | const hasFn = (typeof route.handler.in==='function')
|
53 |
|
54 | return (hasFn===true ? rename(filePath, route.handler.in(route.opts)) : filePath)
|
55 |
|
56 | })()
|
57 |
|
58 |
|
59 | const contentType = mime.lookup(filePath)
|
60 |
|
61 |
|
62 | execute(route, fileRoute, fileLoad, false, (err, data) => {
|
63 |
|
64 | if (err!=null) return next(err)
|
65 |
|
66 |
|
67 | send(res, contentType, data)
|
68 |
|
69 |
|
70 | cache.set(fileRoute, {
|
71 | contentType : contentType,
|
72 | data : data,
|
73 | cache : route.handler.cache
|
74 | })
|
75 |
|
76 | })
|
77 |
|
78 | }
|
79 |
|
80 | } |
\ | No newline at end of file |