forked from fastify/fastify-autoload
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
67 lines (60 loc) · 1.71 KB
/
index.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
65
66
67
'use strict'
const fs = require('fs')
const path = require('path')
const steed = require('steed')
module.exports = function (fastify, opts, next) {
const defaultPluginOptions = opts.options || {}
fs.readdir(opts.dir, function (err, list) {
if (err) {
next(err)
return
}
steed.map(list, (file, cb) => {
const toLoad = path.join(opts.dir, file)
fs.stat(toLoad, (err, stat) => {
if (err) {
cb(err)
return
}
cb(null, { file: toLoad, stat })
})
}, (err, stats) => {
if (err) {
next(err)
return
}
for (let i = 0; i < stats.length; i++) {
const { stat, file } = stats[i]
if (stat.isFile() && !file.match(/.js$/)) {
continue
}
// TODO handle empty directories
// TODO handle directories with a package.json
if (stat.isFile() || stat.isDirectory()) {
try {
const plugin = require(file)
const pluginOptions = {}
Object.assign(pluginOptions, defaultPluginOptions)
if (plugin.autoPrefix) {
const prefix = pluginOptions.prefix || ''
pluginOptions.prefix = prefix + plugin.autoPrefix
}
if (plugin.prefixOverride !== void 0) {
pluginOptions.prefix = plugin.prefixOverride
}
if (plugin.autoload !== false) {
fastify.register(plugin, pluginOptions)
}
} catch (err) {
next(err)
return
}
}
}
next()
})
})
}
// do not create a new context, do not encapsulate
// same as fastify-plugin
module.exports[Symbol.for('skip-override')] = true