|
| 1 | +const logger = (require("log4js")).getLogger("Backend"); |
| 2 | +const stats = require('./stats'); |
| 3 | +const conf = require('./config'); |
| 4 | +const utils = require('./utils'); |
| 5 | +const express = require('express'); |
| 6 | + |
| 7 | +logger.level = "debug"; |
| 8 | + |
| 9 | + |
| 10 | +function renderError(res: any, dark: boolean = false): void { |
| 11 | + return res.render('error', {dark: dark}); |
| 12 | +} |
| 13 | + |
| 14 | +async function renderUser(res: any, username: string, dark: boolean = false): Promise<void> { |
| 15 | + if (! await utils.isAuthenticated(username)) { |
| 16 | + renderError(res, dark); |
| 17 | + } else { |
| 18 | + const resp = await stats.analyseUser(username); |
| 19 | + resp['dark'] = dark; |
| 20 | + res.render('user', resp); |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +async function renderRepo(res: any, username: string, repo: string, dark: boolean = false): Promise<void> { |
| 25 | + if (! await utils.isExistRepo(username, repo)) { |
| 26 | + renderError(res, dark); |
| 27 | + } else { |
| 28 | + const resp = await stats.analyseRepo(username, repo); |
| 29 | + resp['dark'] = dark; |
| 30 | + res.render('repo', resp); |
| 31 | + } |
| 32 | +} |
| 33 | +export function createServer(): void { |
| 34 | + const app = express(); |
| 35 | + |
| 36 | + app.set('views', __dirname + '/views'); |
| 37 | + app.set("view engine", "ejs"); |
| 38 | + |
| 39 | + app.get('/', function (req: any, res: any) { |
| 40 | + res.render('index'); |
| 41 | + }); |
| 42 | + |
| 43 | + app.get('/user/:user/', async function (req: any, res: any) { |
| 44 | + res.type('svg'); |
| 45 | + |
| 46 | + const dark: boolean = req.query['theme'] === 'dark', |
| 47 | + username: string = req.params['user']; |
| 48 | + |
| 49 | + try { await renderUser(res, username, dark) } catch { renderError(res, dark) } |
| 50 | + }); |
| 51 | + |
| 52 | + app.get('/repo/:user/:repo/', async function (req: any, res: any) { |
| 53 | + res.type('svg'); |
| 54 | + |
| 55 | + const dark: boolean = req.query['theme'] === 'dark', |
| 56 | + username = req.params['user'], |
| 57 | + repo = req.params['repo']; |
| 58 | + |
| 59 | + try { await renderRepo(res, username, repo, dark) } catch { renderError(res, dark) } |
| 60 | + }); |
| 61 | + |
| 62 | + app.listen(conf.port, () => |
| 63 | + logger.info(`Starting deployment server at http://127.0.0.1:${conf.port}/.`)); |
| 64 | +} |
0 commit comments