91 lines
2.2 KiB
JavaScript
91 lines
2.2 KiB
JavaScript
/* --- IMPORTS -------------------------- */
|
|
|
|
const config = require('config');
|
|
const tracer = require('tracer');
|
|
|
|
const express = require('express');
|
|
const bodyParser = require('body-parser');
|
|
const concatStream = require('concat-stream');
|
|
|
|
const fs = require('fs');
|
|
const os = require('os');
|
|
const path = require('path');
|
|
|
|
/* --- SETUP ---------------------------- */
|
|
|
|
// Logger
|
|
global.logger = tracer.console({
|
|
level: config.get('logger.level'),
|
|
format: config.get('logger.format'),
|
|
dateformat: config.get('logger.datetime')
|
|
});
|
|
|
|
// Express
|
|
const app = express();
|
|
app.use((req, res, next) => {
|
|
req.pipe(concatStream((data) => {
|
|
req.rawBody = data;
|
|
next();
|
|
}));
|
|
});
|
|
app.use(bodyParser.json());
|
|
app.use(bodyParser.urlencoded({ 'extended': false }));
|
|
|
|
/* --- FUNCTION ------------------------- */
|
|
|
|
function mkdir(dir) {
|
|
if (fs.existsSync(dir)) {
|
|
return;
|
|
}
|
|
|
|
let d = path.dirname(dir);
|
|
if (!fs.existsSync(d)) {
|
|
mkdir(d);
|
|
}
|
|
fs.mkdirSync(dir);
|
|
}
|
|
|
|
function toOsPath(urlPath) {
|
|
return config.get('maven.dir') + urlPath.substr(config.get('maven.url').length + 1);
|
|
}
|
|
|
|
/* --- ROUTING -------------------------- */
|
|
|
|
app.all('*', (req, res, next) => {
|
|
global.logger.trace('Path: %s | Method: %s', req.originalUrl, req.method);
|
|
next();
|
|
});
|
|
|
|
app.route(`/${config.get('maven.url')}/*`)
|
|
.get((req, res) => {
|
|
let osPath = toOsPath(req.path);
|
|
fs.exists(osPath, (value) => {
|
|
if (!value) {
|
|
res.status(404).send();
|
|
} else {
|
|
res.status(200);
|
|
res.sendFile(osPath);
|
|
}
|
|
});
|
|
})
|
|
.put((req, res) => {
|
|
let osPath = toOsPath(req.path);
|
|
mkdir(path.dirname(osPath));
|
|
|
|
fs.writeFile(osPath, req.rawBody, (err) => {
|
|
if (err) {
|
|
global.logger.error(err);
|
|
res.status(500).send();
|
|
} else {
|
|
res.status(200).send();
|
|
}
|
|
});
|
|
});
|
|
|
|
/* --- START APP ------------------------ */
|
|
|
|
const host = config.get('web.host'),
|
|
port = config.get('web.port')
|
|
global.logger.info('Start server :: %s:%s', host, port);
|
|
app.listen(port, host);
|