-
Notifications
You must be signed in to change notification settings - Fork 0
/
public.js
84 lines (69 loc) · 2.63 KB
/
public.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
const srcExpress = require('express');
const coreExpress = require('./express');
const config = require('./config');
const middleware = require('./middleware');
// All public of the module
const source = {};
/**
* Initializes publics based on the provided configuration and adds them to
* the public collection.
*
* @return void
*/
function loadPublic() {
for (var moduleName in config.source) {
source[moduleName] = {};
const configPublic = config.source[moduleName].public;
if (configPublic !== null) {
for (var endpoint in configPublic) {
const public = configPublic[endpoint];
const publicMiddleware = [];
if (typeof public !== 'object') {
throw new Error(`Invalid public for module "${moduleName}" and public "${endpoint}"`);
}
if (typeof public.path !== 'string') {
throw new Error(`Invalid public for module "${moduleName}" and public "${endpoint}"`);
}
if (Array.isArray(public.middleware)) {
for (var selectedMiddleware of public.middleware) {
if (typeof selectedMiddleware === 'string') {
selectedMiddleware = [selectedMiddleware];
} else if (!Array.isArray(selectedMiddleware)) {
throw new Error(`Invalid public middleware for module "${moduleName}" and public "${endpoint}"`);
}
const middlewareModuleName = selectedMiddleware[1] ? selectedMiddleware[0] : moduleName;
const middlewareName = selectedMiddleware[1] || selectedMiddleware[0];
if (typeof middleware.source[middlewareModuleName] === 'undefined') {
throw new Error(`Could not find middleware "${middlewareModuleName}, ${middlewareName}" for module "${moduleName}" and public "${endpoint}"`);
}
if (typeof middleware.source[middlewareModuleName][middlewareName] === 'undefined') {
throw new Error(`Could not find middleware "${middlewareModuleName}, ${middlewareName}" for module "${moduleName}" and public "${endpoint}"`);
}
publicMiddleware.push(middleware.source[middlewareModuleName][middlewareName]);
}
}
publicMiddleware.push(
srcExpress.static(public.path)
);
source[moduleName][endpoint] = publicMiddleware;
}
}
}
}
/**
* Embed all public in the collection into Express.
*
* @return void
*/
function publish() {
for (var moduleName in source) {
for (var endpoint in source[moduleName]) {
coreExpress.source.instance.use(endpoint, source[moduleName][endpoint]);
}
}
}
module.exports = {
source,
loadPublic,
publish
};