swaf/src/components/AutoUpdateComponent.ts

54 lines
1.7 KiB
TypeScript
Raw Normal View History

import {Router} from "express";
2020-05-05 15:19:23 +02:00
import config from "config";
import * as child_process from "child_process";
import ApplicationComponent from "../ApplicationComponent";
import {ForbiddenHttpError} from "../HttpError";
import Logger from "../Logger";
export default class AutoUpdateComponent extends ApplicationComponent<void> {
public async checkSecuritySettings(): Promise<void> {
this.checkSecurityConfigField('gitlab_webhook_token');
}
public async init(router: Router): Promise<void> {
router.post('/update/push.json', (req, res) => {
2020-05-05 15:19:23 +02:00
const token = req.header('X-Gitlab-Token');
if (!token || token !== config.get<string>('gitlab_webhook_token')) throw new ForbiddenHttpError('Invalid token', req.url);
this.update(req.body).catch(Logger.error);
2020-05-05 15:19:23 +02:00
res.json({
'status': 'ok',
});
});
}
private async update(params: any) {
Logger.info('Update params:', params);
2020-05-05 15:19:23 +02:00
try {
Logger.info('Starting auto update...');
2020-06-15 12:58:27 +02:00
// Fetch
await this.runCommand(`git pull`);
2020-05-05 15:19:23 +02:00
// Install new dependencies
await this.runCommand(`yarn install --production=false`);
// Process assets
await this.runCommand(`yarn dist`);
// Stop app
await this.app!.stop();
2020-05-05 15:19:23 +02:00
Logger.info('Success!');
} catch (e) {
Logger.error(e, 'An error occurred while running the auto update.');
}
}
private async runCommand(command: string): Promise<void> {
2020-05-05 15:19:23 +02:00
Logger.info(`> ${command}`);
Logger.info(child_process.execSync(command).toString());
}
}