forked from simrail/simrail.pro
103 lines
3.0 KiB
TypeScript
103 lines
3.0 KiB
TypeScript
import express from 'express';
|
|
import { MLog } from '../mongo/logs.js';
|
|
import { fileURLToPath } from 'node:url';
|
|
import path from 'node:path';
|
|
import dayjs from 'dayjs';
|
|
import { PlayerUtil } from '../util/PlayerUtil.js';
|
|
import { msToTime } from '../util/time.js';
|
|
|
|
const __filename = fileURLToPath(import.meta.url);
|
|
const __dirname = path.dirname(__filename);
|
|
|
|
|
|
export class ApiModule {
|
|
public static load() {
|
|
const app = express();
|
|
|
|
app.set('view engine', 'ejs');
|
|
app.set('views', __dirname + '/views')
|
|
|
|
app.get('/', async (req, res) => {
|
|
const records = await MLog.find()
|
|
.sort({ leftDate: -1 })
|
|
.limit(30)
|
|
res.render('index.ejs', {
|
|
records,
|
|
dayjs,
|
|
msToTime
|
|
});
|
|
})
|
|
|
|
const generateSearch = (regex: RegExp) => [
|
|
{
|
|
stationName: { $regex: regex },
|
|
},
|
|
{
|
|
userUsername: { $regex: regex },
|
|
},
|
|
{
|
|
stationShort: { $regex: regex },
|
|
},
|
|
{
|
|
userSteamId: { $regex: regex },
|
|
},
|
|
{
|
|
server: { $regex: regex },
|
|
}
|
|
]
|
|
|
|
app.get('/search', async (req, res) => {
|
|
if (!req.query.q) return res.redirect('/');
|
|
const s = req.query.q.toString().split(',').map(x => new RegExp(x, "i"));
|
|
|
|
const records = await MLog.aggregate([
|
|
{
|
|
$match: {
|
|
$and: [
|
|
...s.map(x => ({ $or: generateSearch(x) }))
|
|
]
|
|
}
|
|
}
|
|
])
|
|
.sort({ leftDate: -1 })
|
|
.limit(30)
|
|
res.render('search.ejs', {
|
|
records,
|
|
dayjs,
|
|
q: req.query.q,
|
|
msToTime
|
|
});
|
|
})
|
|
|
|
app.get('/details/:id', async (req, res) => {
|
|
if (!req.params.id) return res.redirect('/');
|
|
const record = await MLog.findOne({ id: req.params.id });
|
|
const player = await PlayerUtil.getPlayer(record?.userSteamId!);
|
|
|
|
res.render('details.ejs', {
|
|
record,
|
|
dayjs,
|
|
player,
|
|
msToTime
|
|
});
|
|
})
|
|
|
|
app.get('/api/last', async (req, res) => {
|
|
const records = await MLog.find()
|
|
.sort({ leftDate: -1 })
|
|
.limit(30)
|
|
res.json({ code: 200, records });
|
|
})
|
|
|
|
app.get('/api/search', async (req, res) => {
|
|
if (!req.query.q) return res.send('invalid');
|
|
const records = await MLog.find({ $text: { $search: req.query.q as string } })
|
|
.sort({ leftDate: -1 })
|
|
.limit(30)
|
|
|
|
res.json({ code: 200, records });
|
|
})
|
|
|
|
app.listen(2005);
|
|
}
|
|
} |