@daiyu-5577/quickbuild
Version:
front-end build service
182 lines (181 loc) • 7.08 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import express from 'express';
import { createServer } from "http";
import { Server } from "socket.io";
import cors from 'cors';
import path from 'path';
import chalk from 'chalk';
import controller from './controller.js';
import controller_page from './controller.page.js';
import controller_io from './controller.io.js';
import Builder from '../commandBuild/index.js';
import fs from 'fs-extra';
import logger from '../../utils/log.js';
import { startCron } from '../../utils/cron.js';
import { decrypt } from '../../utils/crypto.js';
import { loadDatabase } from '../../database/index.js';
import swaggerUi from 'swagger-ui-express';
import swaggerJSDoc from 'swagger-jsdoc';
const __dirname = new URL('.', import.meta.url).pathname;
const swaggerSpec = swaggerJSDoc({
failOnErrors: true,
definition: {
openapi: '3.0.0',
info: {
title: 'Quickbuild Api',
version: '1.0.0',
},
},
apis: [
path.join(__dirname, './controller*'),
],
});
class BaseClass {
add(name, instance) {
this[name] = instance;
}
}
export default class BuildServer extends BaseClass {
constructor(props) {
super();
this.app = express();
this.httpServer = createServer(this.app);
this.io = new Server(this.httpServer, {
path: '/ws/',
pingTimeout: 20000,
pingInterval: 6000,
maxHttpBufferSize: 1e8 * 60,
});
this.port = 3000;
this.database = new Map();
this.noticeJson = [];
const { port } = props;
this.port = port || this.port;
const builder = new Builder({
buildServer: this,
});
this.app.set('builder', builder);
this.app.set('io', this.io);
this.app.set('port', this.port);
this.builder = builder;
}
use(name, instance) {
this[name] = instance;
this.app.set(name, instance);
}
init() {
return __awaiter(this, void 0, void 0, function* () {
yield this.getDatabase();
yield this.getNoticeJson();
this.app.use('/static', express.static(path.resolve(__dirname, '../../static'), {
extensions: ['html', 'js', 'css'],
}));
this.app.use(express.json({ limit: '50mb' }));
this.app.use((req, res, next) => __awaiter(this, void 0, void 0, function* () {
var _a;
const excludePaths = [
'/static',
'/page',
'/api/getAllTask',
'/api/getAllPackage',
'/api/getAllLog',
'/api/getAllBackup',
'/api/showLog',
];
if (excludePaths.some(v => req.path.startsWith(v)))
return next();
if (req.path.startsWith('/api/notify') && ((_a = req.body) === null || _a === void 0 ? void 0 : _a.type) == 'on:msg-build')
return next();
let userInfo = '';
const token = req.get('user-token') || req.query.token;
if (token) {
try {
userInfo = yield decrypt(token);
const userInfoObj = JSON.parse(userInfo);
req.userInfo = userInfoObj;
}
catch (error) {
next('invalid token');
return;
}
}
logger.log({
level: 'http',
message: `Request: ${req.method} ${req.url}`,
userInfo,
headers: req.headers,
body: req.body,
});
const originalEnd = res.end;
res.end = function (chunk, encoding, callback) {
logger.log({
level: 'http',
message: `Response: ${req.method} ${req.url}`,
code: res.statusCode,
headers: req.headers,
body: !!chunk && chunk instanceof Buffer ? chunk.toString('utf8') : ''
});
originalEnd.call(this, chunk, encoding, callback);
};
next();
}));
this.app.use(cors({
origin: true,
methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Debug'],
credentials: true,
}));
this.app.use('/api', controller);
this.app.use('/page', controller_page);
this.app.use('/apiDocs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
controller_io.use(this).start();
this.app.use((err, req, res, next) => {
const errorMsg = err instanceof Error ? err.stack : typeof err == 'string' ? err : JSON.stringify(err);
if (res.headersSent) {
console.error('errorHandler: ' + errorMsg);
next(err);
return;
}
res.status(500);
res.send({
message: errorMsg,
success: false,
});
});
});
}
getDatabase() {
return __awaiter(this, void 0, void 0, function* () {
const database = yield loadDatabase();
this.app.set('database', database);
this.database = database;
});
}
getNoticeJson() {
return __awaiter(this, void 0, void 0, function* () {
const noticePath = path.resolve(process.cwd(), 'notice.json');
if (!fs.existsSync(noticePath))
return;
const noticeJson = fs.readJSONSync(noticePath);
this.app.set('noticeJson', noticeJson);
this.noticeJson = noticeJson;
});
}
start() {
return __awaiter(this, void 0, void 0, function* () {
yield this.init();
startCron();
this.httpServer.listen(this.port, () => {
console.log(chalk.green(`server start listening on port ${this.port}`));
});
});
}
}