/
server.js
91 lines (73 loc) · 1.94 KB
/
server.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
'user strict';
var restify = require('restify');
var fs = require('fs');
/**
* Computes the hash (SHA1) of a file.
* <p>
* By default, local Maven repositories do not contain
* hashes as we do not activate the profiles. So, we compute them on the fly.
* </p>
*
* @param filePath
* @param res
* @param next
* @returns nothing
*/
function computeSha1(filePath, res, next) {
var crypto = require('crypto'),
hash = crypto.createHash('sha1'),
stream = fs.createReadStream(filePath);
stream.on('data', function (data) {
hash.update(data, 'utf8')
});
stream.on('end', function () {
var result = hash.digest('hex');
res.end(result);
next();
});
}
/**
* The function that handles the response for the "redirect" operation.
* @param req
* @param res
* @param next
* @returns nothing
*/
function respond(req, res, next) {
var fileName = req.params.a +
'-' + req.params.v +
'.' + req.params.p;
var filePath = '/home/maven/repository/' +
req.params.g.replace('.','/') +
'/' + req.params.a +
'/' + req.params.v +
'/' + fileName;
fs.exists(filePath, function(exists){
if (filePath.indexOf('.sha1', filePath.length - 5) !== -1) {
filePath = filePath.slice(0,-5);
computeSha1(filePath,res, next);
}
else if (! exists) {
res.writeHead(400, {'Content-Type': 'text/plain'});
res.end('ERROR File ' + filePath + ' does NOT Exists');
next();
}
else {
res.writeHead(200, {
'Content-Type': 'application/octet-stream',
'Content-Disposition' : 'attachment; filename=' + fileName});
fs.createReadStream(filePath).pipe(res);
next();
}
});
}
// Server setup
const server = restify.createServer({
name: 'mock-for-nexus-api',
version: '1.0.0'
});
server.use(restify.plugins.queryParser());
server.get('/redirect', respond);
server.listen(9090, function() {
console.log('%s listening at %s', server.name, server.url);
});