-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
229 lines (194 loc) · 7.11 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
/*!
* Express Route-Magic v2.0.8
* (c) 2021 Calvin Tan
* Released under the MIT License.
*/
'use strict'
// modules
const fs = require('fs')
const path = require('path')
const hlp = require('./lib/helpers.js')
// defaults
const Magic = {
_moduleName: 'express-routemagic',
_routesFolder: 'routes',
_allowSameName: false,
_debug: console.log,
_logMapping: false,
_invokerPath: path.join(__dirname, './../../')
}
// properties that require getters and setters
Object.defineProperties(Magic, {
invokerPath: {
get() {
return this._invokerPath
},
set(val) {
let fail = hlp.argFail('string', val, 'invokerPath', 'The path of where you invoked magic must be a valid `string`. Typically it is `__dirname`.')
if (fail) throw new Error(fail)
this._invokerPath = val
}
},
routesFolder: {
get() {
return this._routesFolder
},
set(val) {
let fail = hlp.argFail('string', val, 'routesFolder', 'This value defaults to \'routes\'. If you change your folder structure to follow you won\'t need this option.')
if (fail) throw new Error(fail)
if (val[val.length - 1] === '/' || val[val.length - 1] === '\\') val = val.substring(0, val.length - 1)
this._routesFolder = val
}
},
ignoreSuffix: {
get() {
return this._ignoreSuffix
},
set(val) {
let fail = hlp.argFail(['string', 'array'], val, 'ignoreSuffix')
if (fail) throw new Error(fail)
this._ignoreSuffix = Array.isArray(val) ? val : [val]
}
},
allowSameName: {
get() {
return this._allowSameName
},
set(val) {
let fail = hlp.argFail('boolean', val, 'allowSameName')
if (fail) throw new Error(fail)
this._allowSameName = val
}
},
logMapping: {
get() {
return this._logMapping
},
set(val) {
let fail = hlp.argFail('boolean', val, 'logMapping')
if (fail) throw new Error(fail)
this._logMapping = val
}
},
debug: {
get() {
return this._debug
},
set(val) {
let fail = hlp.argFail('function', val, 'debug')
if (fail) throw new Error(fail)
this._debug = val
}
}
})
// methods
Magic.use = function(app, relativeRoutesFolderOrOptions) {
if (!app) throw new Error('Invalid argument: Express `app` instance must be passed in as 1st argument.')
this.app = app
if (!hlp.argFail('string', relativeRoutesFolderOrOptions)) {
this.routesFolder = path.normalize(relativeRoutesFolderOrOptions)
} else if (!hlp.argFail('object', relativeRoutesFolderOrOptions)) {
let options = relativeRoutesFolderOrOptions
// may need debugging module downstream, so assign first.
if (options.debug) this.debug = options.debug
if (relativeRoutesFolderOrOptions.routesFolder) relativeRoutesFolderOrOptions.routesFolder = path.normalize(relativeRoutesFolderOrOptions.routesFolder)
if (relativeRoutesFolderOrOptions.invokerPath) relativeRoutesFolderOrOptions.invokerPath = path.normalize(relativeRoutesFolderOrOptions.invokerPath)
hlp.applyOpts(this, options, [
'routesFolder',
'ignoreSuffix',
'allowSameName',
'debug',
'logMapping',
'invokerPath'
])
}
this.scan(this.absolutePathToRoutesFolder())
}
Magic.scan = function(directory) {
let _folders = []
let _files = []
if (!fs.existsSync(directory)) throw new Error(`Routes folder not found in: ${directory}`)
fs.readdirSync(directory).filter(file => {
// ignore hidden file
if (file.indexOf('.') === 0) return false
// directory
if (fs.lstatSync(path.join(directory, '/', file)).isDirectory()) {
this.push(_folders, file, true)
return false
}
// js files
return (
(file.indexOf('.js') === file.length - '.js'.length) ||
(file.indexOf('.ts') === file.length - '.ts'.length)
)
}).forEach(file => {
if (['index.js', 'index.ts'].indexOf(file) > -1) {
_files.unshift(file)
} else {
this.push(_files, file)
}
})
this.checkConflict(_files, _folders, directory)
// require
this.require(directory, _files)
// scan folders
_folders.forEach(folder => {
this.scan(path.join(directory, '/', folder))
})
}
Magic.push = function(array, payload, isDirectory) {
if (!this.toIgnore(payload, isDirectory)) array.push(payload)
}
Magic.toIgnore = function(payload, isDirectory) {
if (!isDirectory) payload = payload.substring(0, payload.length - 3) // remove the extension
let toIgnore = false
if (this.ignoreSuffix) {
this.ignoreSuffix.forEach(suffix => {
if (payload.indexOf(suffix) !== -1 && payload.indexOf(suffix) === payload.length - suffix.length) {
toIgnore = true
return null
}
})
}
return toIgnore
}
Magic.checkConflict = function(files, folders, directory) {
if (this.allowSameName) return false
files.forEach(file => {
if (folders.indexOf(file.substring(0, file.length - 3)) !== -1) throw new Error(`Folder and file with conflict name: \`${file.substring(0, file.length - 3)}\` in directory: \`${directory}\`.`)
})
}
Magic.require = function(dir, files) {
let apiDirectory = this.apiDirectory(dir)
files.forEach(file => {
let apiPath = this.apiPath(file, apiDirectory)
let route = require(this.absolutePathFile(dir, file))
// ES6 export defauly compatibility
if (typeof route !== 'function') route = route.default
this.app.use(apiPath, route)
if (this.logMapping) this.debug(apiPath + ' => .' + this.pathRelativeToInvoker(dir, file))
})
}
Magic.apiDirectory = function(dir) {
let apiDir = path.relative(this.absolutePathToRoutesFolder(), dir)
return (apiDir.length === 0) ? path.normalize('/') : path.normalize(path.join('/', apiDir))
}
Magic.apiPath = function(file, apiDir) {
apiDir = path.normalize(apiDir)
// TODO: To support passing array to
// have to check whether the apiDir have any commas. if yes can indicate a ['/route1', '/route2'] kind.
// also need to check if file have any commans. if yes can indicate a ['/route1/filename1', '/route2/filename1', '/route1/filename2', '/route2/filename2'] kind of situation.
let apiPath = (['index.js', 'index.ts'].indexOf(file) > -1) ? apiDir : path.join(apiDir, file.substring(0, file.length - 3))
apiPath = apiPath.replace(/\\/g, '/')
return apiPath
}
Magic.absolutePathToRoutesFolder = function() {
return path.join(this.invokerPath, this.routesFolder)
}
Magic.absolutePathFile = function(dir, file) {
return path.join(dir, file)
}
Magic.pathRelativeToInvoker = function (dir, file) {
return path.join(path.relative(this.invokerPath, dir), file)
}
module.exports = Object.create(Magic)