UNPKG

2.67 kBJavaScriptView Raw
1'use strict'
2
3const path = require('path')
4const async = require('async')
5
6/**
7 * Parse and validate a route.
8 * @public
9 * @param {Object} route - A single route configuration.
10 * @returns {Object} route - A single validated route configuration.
11 * @throws {Error}
12 */
13const _route = function(route) {
14
15 // Copy object to prevent changes by reverence
16 route = Object.assign({}, route)
17
18 // Check if route has a name
19 // The name is required to output informative messages and errors
20 if (route.name==null || route.name==='') throw new Error('Missing name property in route')
21
22 // Check if route has a path and a handler
23 if (route.path==null) throw new Error(`Missing path property in route '${ route.name }'`)
24 if (route.handler==null) throw new Error(`Missing handler property in route '${ route.name }'`)
25
26 // Check if path is relative
27 if (path.isAbsolute(route.path)===true) throw new Error(`Path in route '${ route.name }' must be relative`)
28
29 // Check if handler is a string or function
30 if (typeof route.handler==='string') route.handler = require(route.handler)
31 if (typeof route.handler!=='function') throw new Error(`Handler in route '${ route.name }' is not a function nor a string`)
32
33 // Provide fallbacks
34 if (route.opts==null) route.opts = {}
35
36 return route
37
38}
39
40/**
41 * Parse and validate a path.
42 * @public
43 * @param {String} filePath - Path to a folder or file.
44 * @returns {String} filePath - Validated and absolute path to a folder or file.
45 */
46const _path = function(filePath) {
47
48 // Make filePath absolute
49 filePath = path.resolve(filePath)
50
51 return filePath
52
53}
54
55/**
56 * Parse and validate options.
57 * @public
58 * @param {Object} opts - Additional optional options.
59 * @returns {Object} opts - Validated additional optional options.
60 */
61const _opts = function(opts) {
62
63 // Copy object to prevent changes by reverence
64 opts = Object.assign({}, opts)
65
66 // Set default value when an option is missing or has an incorrect type
67 opts.ignore = (Array.isArray(opts.ignore)===true ? opts.ignore : [])
68 opts.polling = (opts.polling===true ? true : false)
69 opts.verbose = (opts.verbose===true ? true : false)
70 opts.open = (opts.open===false ? false : true)
71
72 return opts
73
74}
75
76/**
77 * Parse and validate callbacks.
78 * @public
79 * @param {?Function} next - A callback that handles a response.
80 * @returns {Function} next - A validated callback that handles a response and throws errors.
81 */
82const _next = function(next) {
83
84 // Ensure that next is a function
85 if (typeof next!=='function') next = (err) => {
86
87 if (err!=null) throw err
88
89 }
90
91 return next
92
93}
94
95/**
96 * @public
97 */
98module.exports = {
99 route : _route,
100 path : _path,
101 opts : _opts,
102 next : _next
103}
\No newline at end of file