/
media.js
173 lines (171 loc) · 4.52 KB
/
media.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
var path = require('path')
, fs = require('fs')
, _ = require('underscore');
/**
*
*/
var rootDirectory = __dirname
, errorPath = rootDirectory + '/error/index';
/**
*
* @param config
* @returns {routeRequest}
*/
module.exports = function (config) {
rootDirectory = config.rootDirectory;
errorPath = config.errorPath ? config.errorPath : errorPath;
return routeRequest;
};
/**
*
* @param req
* @param res
* @param next
*/
var routeRequest = function (req, res, next) {
var accepts = req.headers['accept'],
mediaTypes = accepts.split(','),
fileExtensions = _.map(mediaTypes, function (mediaType) {
return mediaType.split(/[\+\/]/).pop();
});
if (_.contains(fileExtensions, '*') || _.contains(fileExtensions, 'json')) {
fileExtensions.push('js');
mediaTypes.push('application/json');
}
var mediaPath = req.originalUrl.sanitizePath().splitPath(),
params = {};
mediaPath.testPathParts(rootDirectory, params, function (finalPath, params) {
findExistingFileExt(finalPath, fileExtensions, mediaTypes, function (filePathWithExtension, fileExt, mediaType) {
mediaResponse(fileExt, mediaType, filePathWithExtension, req, res, params, next);
});
});
};
/**
*
* @param mediaPath
* @param fileExtensions
* @param mediaTypes
* @param callback
*/
function findExistingFileExt(mediaPath, fileExtensions, mediaTypes, callback) {
var foundFile = false;
_.each(fileExtensions, function (fileExt, index) {
var mediaType = mediaTypes[index]
, fileInformation = mediaType.split(/[\/]/).pop()
, fileName = fileInformation.split(/[\+]/).shift();
if (fileName === fileExt || fileExt === 'js') {
fileName = 'index';
}
fs.exists(mediaPath + '/' + fileName + '.' + fileExt, function (exists) {
if (exists && !foundFile) {
foundFile = true;
callback(mediaPath + '/' + fileName + '.' + fileExt, fileExt, mediaType);
}
});
fs.exists(mediaPath + '.' + fileExt, function (exists) {
if (exists && !foundFile) {
foundFile = true;
callback(mediaPath + '.' + fileExt, fileExt, mediaType);
}
});
// Handling the case where no file was found for that media Type
if (index >= (fileExtensions.length - 1)) {
setTimeout(function () {
if (!foundFile) {
foundFile = true;
callback(errorPath + '.html', 'html', 'text/html');
}
}, 0);
}
});
}
/**
*
* @param fileExt
* @param mediaType
* @param mediaPath
* @param req
* @param res
* @param params
* @param next
*/
function mediaResponse(fileExt, mediaType, mediaPath, req, res, params, next) {
// Set the response content-type header to match the accept header
res.setHeader('Content-Type', mediaType);
switch (fileExt) {
case 'json':
res.status(200).json(require(mediaPath));
break;
case 'js':
req.params = params;
require(mediaPath)[req.method.toLowerCase()](req, res, next);
break;
default:
fs.readFile(mediaPath, function (err, data) {
if (err) {
res.setHeader('Content-Type', 'application/json');
res.status(200).json({
error: 'media-type: ' + mediaType + ' not supported.'
});
return;
}
res.send(data);
});
break;
}
}
/**
*
* @returns {string}
*/
String.prototype.sanitizePath = function () {
return this.replace(/\?.*$/, '');
};
/**
*
* @returns {Array}
*/
String.prototype.splitPath = function () {
return this.split('/').filter(function (part) {
return part.length;
});
};
/**
*
* @param rootPath
* @param params
* @param callback
* @returns {Array}
*/
Array.prototype.testPathParts = function (rootPath, params, callback) {
var that = this;
if (this.length === 0) {
callback(rootPath, params);
return this;
}
var pathSegment = this.shift(),
nextPath = path.join(rootPath, pathSegment);
fs.exists(nextPath, function (exists) {
if (exists) {
that.testPathParts(nextPath, params, callback);
} else {
fs.readdir(rootPath, function (err, files) {
var matches;
for (var index in files) {
if (files.hasOwnProperty(index)) {
matches = files[index].match(/:(.*)/);
if (!matches) {
callback(errorPath, params);
return this;
}
params[matches[1]] = pathSegment;
nextPath = path.join(rootPath, files[index]);
that.testPathParts(nextPath, params, callback);
return;
}
}
});
}
});
return this;
};