forked from oat/in-the-database-2
94 lines
2.4 KiB
TypeScript
94 lines
2.4 KiB
TypeScript
import * as express from 'express';
|
|
import * as mongoose from 'mongoose';
|
|
import * as fs from 'fs';
|
|
import * as winston from 'winston';
|
|
|
|
import * as format from './lib/format';
|
|
import { File } from './schema';
|
|
|
|
const config = JSON.parse(fs.readFileSync('./config/config.json', {encoding: 'utf8'}));
|
|
|
|
const db = mongoose.connect(`${config.dbconnectionURL}/${config.dbname}`, {
|
|
useNewUrlParser: true, // idfk what any of this does i just copied an example
|
|
useUnifiedTopology: true,
|
|
useFindAndModify: false,
|
|
useCreateIndex: true
|
|
});
|
|
|
|
const logger = winston.createLogger({
|
|
level: 'info',
|
|
format: winston.format.combine(
|
|
winston.format.timestamp(),
|
|
winston.format.printf(log => `${format.formatTime(new Date(log.timestamp))} | ${log.message}`)
|
|
),
|
|
transports: [
|
|
new winston.transports.File({filename: `${config.name}-error.log`, level: 'error'}),
|
|
new winston.transports.File({filename: `${config.name}.log`}),
|
|
new winston.transports.Console({
|
|
format: winston.format.combine(
|
|
winston.format.colorize(),
|
|
winston.format.timestamp(),
|
|
winston.format.printf(log =>
|
|
`${format.formatTime(new Date(log.timestamp))} - [${log.level}] ${log.message}`
|
|
)
|
|
),
|
|
level: process.env.DEBUG === 'true' ? 'silly' : 'info'
|
|
})
|
|
]
|
|
});
|
|
|
|
function returnStatic(page) {
|
|
return (req, res) => {
|
|
fs.readFile(`src/html/${page}`, 'utf8', (err, data) => {
|
|
if (err) throw err;
|
|
res.send(data);
|
|
});
|
|
};
|
|
}
|
|
|
|
logger.info('connecting to mongodb database');
|
|
db.then(() => {
|
|
logger.info('connected to database!');
|
|
|
|
const app = express();
|
|
|
|
app.use(express.urlencoded({ extended: true }));
|
|
|
|
app.set('db', db);
|
|
app.set('config', config);
|
|
app.set('logger', logger);
|
|
|
|
app.get('/upload', returnStatic('upload.html'));
|
|
|
|
app.post('/upload', async (req, res) => { // only for testing, very abusable
|
|
const file = new File(req.body);
|
|
await file.save();
|
|
|
|
res.send('uploaded file');
|
|
});
|
|
|
|
app.get('/list', async (req, res) => { // only for testing
|
|
let docs = await File.find({});
|
|
docs = docs.map(d => {
|
|
const keys = Object.keys(d.toObject()).filter(k => !k.startsWith('_'));
|
|
const obj = {};
|
|
for (const key of keys) obj[key] = d[key];
|
|
|
|
return obj;
|
|
});
|
|
res.send(JSON.stringify(docs));
|
|
});
|
|
|
|
app.get('/', (req, res) => {
|
|
res.send('wip');
|
|
});
|
|
|
|
|
|
app.get('*', (req, res) => {
|
|
res.status(404).send('404');
|
|
});
|
|
|
|
app.listen(config.port, () => {
|
|
logger.info(`expressjs server launched on port ${config.port}, should now function properly`);
|
|
});
|
|
}); |