UNPKG

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