UNPKG

1.33 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
8const { $customPath, $customCallback, $customTimestamp } = require('../symbols')
9
10module.exports = {
11 schema: {
12 custom: ['function', 'string'],
13 watch: {
14 type: 'boolean',
15 defaultValue: false
16 }
17 },
18 validate: async mapping => {
19 if (typeof mapping.custom === 'string') {
20 mapping[$customPath] = path.join(mapping.cwd, mapping.custom)
21 mapping[$customCallback] = require(mapping[$customPath])
22 if (mapping.watch) {
23 mapping[$customTimestamp] = (await statAsync(mapping[$customPath])).mtimeMs
24 }
25 } else {
26 mapping[$customCallback] = mapping.custom
27 }
28 },
29 redirect: async ({ mapping, match, request, response }) => {
30 if (mapping[$customTimestamp]) {
31 const timestamp = (await statAsync(mapping[$customPath])).mtimeMs
32 if (timestamp !== mapping[$customTimestamp]) {
33 mapping[$customTimestamp] = timestamp
34 delete require.cache[mapping[$customPath]]
35 mapping[$customCallback] = require(mapping[$customPath])
36 }
37 }
38 // Include timeout?
39 const parameters = [request, response].concat([].slice.call(match, 1))
40 return mapping[$customCallback].apply(mapping, parameters)
41 }
42}