1 | 'use strict'
|
2 |
|
3 | const fs = require('fs')
|
4 | const path = require('path')
|
5 | const util = require('util')
|
6 | const statAsync = util.promisify(fs.stat)
|
7 |
|
8 | module.exports = {
|
9 | schema: {
|
10 | custom: ['function', 'string'],
|
11 | watch: {
|
12 | type: 'boolean',
|
13 | defaultValue: false
|
14 | }
|
15 | },
|
16 | validate: async mapping => {
|
17 | if (typeof mapping.custom === 'string') {
|
18 | mapping._path = path.join(mapping.cwd, mapping.custom)
|
19 | mapping._callback = require(mapping._path)
|
20 | if (mapping.watch) {
|
21 | mapping._timestamp = (await statAsync(mapping._path)).mtimeMs
|
22 | }
|
23 | } else {
|
24 | mapping._callback = mapping.custom
|
25 | }
|
26 | },
|
27 | redirect: async ({ mapping, match, request, response }) => {
|
28 | if (mapping._timestamp) {
|
29 | const timestamp = (await statAsync(mapping._path)).mtimeMs
|
30 | if (timestamp !== mapping._timestamp) {
|
31 | mapping._timestamp = timestamp
|
32 | delete require.cache[mapping._path]
|
33 | mapping._callback = require(mapping._path)
|
34 | }
|
35 | }
|
36 |
|
37 | const parameters = [request, response].concat([].slice.call(match, 1))
|
38 | return mapping._callback.apply(mapping, parameters)
|
39 | }
|
40 | }
|