Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
72 lines (62 loc) · 1.6 KB
/
Copy pathindex.js
File metadata and controls
72 lines (62 loc) · 1.6 KB
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
// import _ from 'lodash';
import express from 'express';
import path from 'path';
import serveIndex from 'serve-index';
import favicon from 'serve-favicon';
import process from 'process';
import logger from './logger';
import {
BASE_URL,
PORT,
DUMP_DIRECTORY,
DUMP_PATH,
API_KEY
} from './config';
import { backup, setupChangefeeds } from './backup';
import db from './db';
// ExpressJS: routes
const app = express();
const checkApiKey = function (req, res, next) {
if( API_KEY && req.query.apiKey != API_KEY ){
res.send( 401, "Unauthorized" );
} else {
next();
}
};
app.use(favicon(path.join(__dirname, 'logo.png')));
app.use(`/${DUMP_PATH}`, serveIndex( path.join( __dirname, DUMP_DIRECTORY ), { 'icons': true } ) );
app.get(`/${DUMP_PATH}backup`, checkApiKey, ( req, res, next ) => {
backup().then( () => res.status( 202 ).end() ).catch( next );
});
app.get(`/${DUMP_PATH}:fileName`, ( req, res, next ) => {
const { fileName } = req.params;
var options = {
root: path.join( __dirname, DUMP_DIRECTORY ),
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true
}
};
res.sendFile( fileName, options, function ( err ) {
if ( err ) {
next( err );
} else {
logger.info(`Sent ${fileName}`);
}
});
});
// Initialize app
Promise.resolve()
.then( () => db.tryForTable( 'document' ) )
.then( setupChangefeeds )
.then( () => {
app.listen( PORT, () => {
logger.info(`Listening at ${BASE_URL}:${PORT}`);
});
})
.catch( err => {
logger.error(`Init: ${err}`);
process.exit( 1 );
});
export default app;