UNPKG

1.15 kBJavaScriptView Raw
1'use strict'
2
3const fs = require('fs')
4const path = require('path')
5const util = require('util')
6const statAsync = util.promisify(fs.stat)
7
8module.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 // Include timeout?
37 const parameters = [request, response].concat([].slice.call(match, 1))
38 return mapping._callback.apply(mapping, parameters)
39 }
40}