-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathair-drop-flatiron.js
106 lines (80 loc) · 2.66 KB
/
air-drop-flatiron.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
var AirDrop = require('air-drop')
, flatiron = require('flatiron')
, app = flatiron.app
, Path = AirDrop.Path
, fs = require('fs')
, initialized = false
, packages = [];
module.exports = AirDropFlatiron;
//mimic AirDrop but dont use router
function AirDropFlatiron(url) {
var package = AirDrop(url);
//set route only if app.router already defined
if (initialized) {
setRoute(package, app.router);
} else {
packages.push(package);
}
return package;
};
AirDropFlatiron.attach = function attach() {
//add AirDrop to flatiron app
this.AirDrop = AirDropFlatiron;
}
AirDropFlatiron.init = function init(done) {
initialized = true;
//if packages are declare before app.use(flatiron.plugins.http)
if (packages.length) {
packages.forEach(function(package) {
setRoute(package, app.router);
});
delete packages;
}
done();
}
function deliverSource(req, res, is_css) {
return function(err, data) {
var contentType;
if(err) throw err;
if (is_css) {
contentType = "text/css";
} else {
contentType = "application/javascript";
}
res.setHeader("Content-Type", contentType);
res.write(data);
res.end();
};
}
function fetchCb(package, type, filepath) {
return function(cb) {
var path = new Path({type: type, path: filepath, isCss: package.isCss()});
package.readWrapFile(path, cb);
}
}
//make available air-drop routes to director router
function setRoute(package, router) {
var url = package.url.replace('.', '\\.')
, reg_exp = "([\\w\\-\\.\\|]+)"
, is_css = package.isCss();
//duplicated (small adaptation) function from air-drop (@todo: refactoring?)
router.get(url, function() {
package.useCachedResult(package.url, package.source.bind(package), deliverSource(this.req, this.res, is_css));
});
//duplicated (small adaptation) function from air-drop (@todo: refactoring?)
router.get(url + "/include/" + reg_exp, function(filepath) {
var filepath = filepath.replace(/\|/g, "/")
, key = package.url + "/include/" + filepath
, fetchFunc = fetchCb(package, 'include', filepath);
package.useCachedResult(key, fetchFunc, deliverSource(this.req, this.res, is_css));
});
//duplicated (small adaptation) function from air-drop (@todo: refactoring?)
router.get(url + "/require/" + reg_exp, function(filepath, name) {
var req = this.req
, res = this.res
, filepath = filepath.replace(/\|/g, "/")
, key = package.packageName + "/require/" + filepath
, fetchFunc = fetchCb(package, 'require', filepath);
package.useCachedResult(key, fetchFunc, deliverSource(req, res, is_css));
});
}