Skip to content

Commit 8722dce

Browse files
committed
Refactor database connection setup to use a URI; update GitHub app registration URLs; enhance logging for setup processes; improve installation handling in the frontend.
1 parent e5e02c1 commit 8722dce

10 files changed

Lines changed: 66 additions & 73 deletions

File tree

backend/src/app.ts

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,10 @@ class App {
2828
this.e = express();
2929
this.port = port;
3030
logger.info(`Starting application on port ${this.port}`);
31-
if (!process.env.MONGODB_URI) {
32-
throw new Error('MONGODB_URI must be set');
33-
}
34-
this.database = new Database(process.env.MONGODB_URI);
31+
// if (!process.env.MONGODB_URI) {
32+
// throw new Error('MONGODB_URI must be set');
33+
// }
34+
this.database = new Database();
3535
const webhookService = new WebhookService({
3636
url: process.env.WEBHOOK_PROXY_URL,
3737
path: '/api/github/webhooks',
@@ -70,17 +70,19 @@ class App {
7070
this.setupExpress();
7171
logger.info('Express setup complete');
7272

73-
logger.info('Database connecting...');
74-
await this.database.connect();
75-
logger.info('Database connected');
76-
77-
logger.info('Initializing settings...');
78-
await this.initializeSettings();
79-
logger.info('Settings initialized');
73+
if (process.env.MONGODB_URI) {
74+
logger.info('Database connecting...');
75+
await this.database.connect(process.env.MONGODB_URI);
76+
logger.info('Database connected');
8077

81-
logger.info('GitHub App starting...');
82-
await this.github.connect();
83-
logger.info('GitHub App connected');
78+
logger.info('Initializing settings...');
79+
await this.initializeSettings();
80+
logger.info('Settings initialized');
81+
82+
logger.info('GitHub App starting...');
83+
await this.github.connect();
84+
logger.info('GitHub App connected');
85+
}
8486

8587
return this.e;
8688
} catch (error) {
@@ -89,7 +91,6 @@ class App {
8991
logger.error(error.message);
9092
}
9193
logger.debug(error);
92-
process.exit(1);
9394
}
9495
}
9596

backend/src/controllers/setup.controller.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
import { Request, Response } from 'express';
22
import app from '../index.js';
33
import StatusService from '../services/status.service.js';
4+
import logger from '../services/logger.js';
45

56
class SetupController {
67
async registrationComplete(req: Request, res: Response) {
78
try {
9+
logger.info(`GitHub registrationComplete`, req.query);
810
const { code } = req.query;
911
const { html_url } = await app.github.createAppFromManifest(code as string);
1012
res.redirect(`${html_url}/installations/new`);
@@ -15,6 +17,7 @@ class SetupController {
1517

1618
async installComplete(req: Request, res: Response) {
1719
try {
20+
logger.info(`GitHub installComplete`, req.query);
1821
const installationUrl = await app.github.app?.getInstallationUrl();
1922
if (!installationUrl) throw new Error('No installation URL found');
2023
res.redirect(installationUrl);
@@ -34,6 +37,7 @@ class SetupController {
3437

3538
async addExistingApp(req: Request, res: Response) {
3639
try {
40+
logger.info(`GitHub addExistingApp`, req.body);
3741
const { appId, privateKey, webhookSecret } = req.body;
3842

3943
if (!appId || !privateKey || !webhookSecret) {
@@ -101,7 +105,7 @@ class SetupController {
101105

102106
async setupDB(req: Request, res: Response) {
103107
try {
104-
await app.database.connect();
108+
await app.database.connect(req.body.uri);
105109
res.json({ message: 'DB setup started' });
106110
} catch (error) {
107111
res.status(500).json(error);

backend/src/database.ts

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,18 @@
11
import updateDotenv from 'update-dotenv';
22
import logger from './services/logger.js';
3-
import mongoose, { mongo, Schema } from 'mongoose';
3+
import mongoose, { Schema } from 'mongoose';
44
import util from 'util';
5-
import { da } from 'date-fns/locale';
65

76
class Database {
87
mongoose: mongoose.Mongoose | null = null;
9-
mongodbUri: string;
8+
mongodbUri?: string;
109

11-
constructor(mongodbUri: string) {
12-
this.mongodbUri = mongodbUri;
13-
}
14-
15-
async connect() {
16-
//improve the logger message @12:12
10+
constructor() { }
1711

18-
logger.info('Connecting to the database', this.mongodbUri);
19-
if (this.mongodbUri) await updateDotenv({ MONGODB_URI: this.mongodbUri });
12+
async connect(mongodbUri: string) {
13+
logger.info('Connecting to the database', mongodbUri);
2014
try {
21-
this.mongoose = await mongoose.connect(this.mongodbUri, {
15+
this.mongoose = await mongoose.connect(mongodbUri, {
2216
socketTimeoutMS: 90000,
2317
connectTimeoutMS: 60000,
2418
serverSelectionTimeoutMS: 30000,
@@ -41,14 +35,27 @@ class Database {
4135
// logger.debug(`\x1B[0;36mMongoose:\x1B[0m: ${collectionName}.${methodName}` + `(${methodArgs.map(msgMapper).join(', ')})`);
4236
logger.debug(`[Mongoose] ${collectionName}.${methodName}(${methodArgs.map(msgMapper).join(', ')})`);
4337
});
44-
38+
39+
if (mongodbUri) await updateDotenv({ MONGODB_URI: mongodbUri });
40+
this.mongodbUri = mongodbUri;
41+
logger.info('Database connected');
42+
43+
this.setupSchemas();
44+
logger.info('Database schemas setup complete');
4545
} catch (error) {
4646
logger.debug(error);
4747
if (error instanceof Error) {
4848
logger.error(`Database connection error: ${error.message}`);
4949
}
5050
throw error;
5151
}
52+
}
53+
54+
async disconnect() {
55+
await this.mongoose?.disconnect();
56+
}
57+
58+
async setupSchemas() {
5259
mongoose.model('Settings', new mongoose.Schema({
5360
name: String,
5461
value: {}
@@ -361,10 +368,6 @@ class Database {
361368
mongoose.model('Counter', CounterSchema);
362369
}
363370

364-
async disconnect() {
365-
await this.mongoose?.disconnect();
366-
}
367-
368371
}
369372

370373
export default Database;

backend/src/github.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ class GitHub {
116116
getAppManifest(baseUrl: string) {
117117
const manifest = JSON.parse(readFileSync('github-manifest.json', 'utf8'));
118118
const base = new URL(baseUrl);
119-
manifest.url = base.href;
119+
manifest.url = base.href || 'localhost';
120120
manifest.hook_attributes.url = new URL('/api/github/webhooks', base).href;
121121
manifest.setup_url = new URL('/api/setup/install/complete', base).href;
122122
manifest.redirect_url = new URL('/api/setup/registration/complete', base).href;

backend/src/services/query.service.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import { insertUsage } from '../models/usage.model.js';
44
import SeatService, { SeatEntry } from './seats.service.js';
55
import { App, Octokit } from 'octokit';
66
import { MetricDailyResponseType } from '../models/metrics.model.js';
7-
import mongoose from 'mongoose';
87
import metricsService from './metrics.service.js';
98
import teamsService from './teams.service.js';
109
import adoptionService from './adoption.service.js';
@@ -44,7 +43,7 @@ class QueryService {
4443

4544
private async task() {
4645
const queryAt = new Date();
47-
logger.info(`Task started`);
46+
logger.info(`Task started. Last ran at `, this.cronJob.lastDate());
4847
const tasks = [];
4948
for await (const { octokit, installation } of this.app.eachInstallation.iterator()) {
5049
if (!installation.account?.login) return;

frontend/src/app/database/database.component.html

Lines changed: 3 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,20 +6,9 @@
66
<form [formGroup]="dbFormGroup" (ngSubmit)="dbConnect()" class="database-form">
77
<ng-template matStepLabel>Database</ng-template>
88
<mat-form-field>
9-
<mat-label>Hostname</mat-label>
10-
<input matInput formControlName="hostname" placeholder="127.0.0.1">
11-
</mat-form-field>
12-
<mat-form-field>
13-
<mat-label>Port</mat-label>
14-
<input type="number" formControlName="port" matInput placeholder="3306">
15-
</mat-form-field>
16-
<mat-form-field>
17-
<mat-label>Username</mat-label>
18-
<input matInput formControlName="username" placeholder="root">
19-
</mat-form-field>
20-
<mat-form-field>
21-
<mat-label>Password</mat-label>
22-
<input matInput formControlName="password" type="password">
9+
<mat-label>Connection String URI</mat-label>
10+
<input matInput formControlName="uri"
11+
placeholder="mongodb://myDatabaseUser:P%40ssw0rd@cluster0.example.mongodb.net/?retryWrites=true&w=majority">
2312
</mat-form-field>
2413
<div>
2514
</div>

frontend/src/app/database/database.component.ts

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -44,10 +44,7 @@ export class DatabaseComponent implements AfterViewInit {
4444
status?: statusResponse;
4545
isDbConnecting = false;
4646
dbFormGroup = new FormGroup({
47-
hostname: new FormControl('', Validators.required),
48-
port: new FormControl(3306, [Validators.required, Validators.min(1), Validators.max(65535)]),
49-
username: new FormControl('root', Validators.required),
50-
password: new FormControl(''),
47+
uri: new FormControl('', Validators.required)
5148
});
5249

5350
constructor(
@@ -74,10 +71,7 @@ export class DatabaseComponent implements AfterViewInit {
7471
if(this.dbFormGroup.invalid) return;
7572
this.isDbConnecting = true;
7673
this.setupService.setupDB({
77-
host: this.dbFormGroup.value.hostname!,
78-
port: this.dbFormGroup.value.port!,
79-
username: this.dbFormGroup.value.username!,
80-
password: this.dbFormGroup.value.password!,
74+
uri: this.dbFormGroup.value.uri!
8175
}).subscribe(() => {
8276
this.isDbConnecting = false;
8377
this.cdr.detectChanges();

frontend/src/app/install/install.component.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ export class DialogAppComponent {
9696

9797
registerNewApp() {
9898
if (this.organizationFormControl.value) {
99-
this.form.nativeElement.action = `https://github.com/enterprises/${this.organizationFormControl.value}/settings/apps/new?state=abc123`
99+
this.form.nativeElement.action = `https://github.com/organizations/${this.organizationFormControl.value}/settings/apps/new?state=abc123`
100100
}
101101
this.form.nativeElement.submit();
102102
this.dialogRef.close();

frontend/src/app/main/main.component.html

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -53,17 +53,24 @@
5353
</button>
5454
}
5555
<div class="header">
56-
<div *ngIf="installationsService.currentInstallation.asObservable() | async as installation" class="mat-card-avatar" mat-card-avatar style="background-size: cover;"
56+
<div *ngIf="installationsService.currentInstallation.asObservable() | async as installation"
57+
class="mat-card-avatar" mat-card-avatar style="background-size: cover;"
5758
[style.background-image]="'url(' + installation?.account?.avatar_url + ')'">
5859
</div>
59-
<h1>
60-
<mat-select [ngModel]="(installationsService.currentInstallation.asObservable() | async)?.id || 1" (ngModelChange)="installationsService.setInstallation($event)">
61-
<mat-option [value]="1">Enterprise</mat-option>
62-
@for (installation of installationsService.getInstallations() | async; track installation.id) {
63-
<mat-option [value]="installation.id">{{ installation.account?.login }}</mat-option>
64-
}
65-
</mat-select>
66-
</h1>
60+
<ng-container *ngIf="installationsService.getInstallations() | async as installations">
61+
<h1>
62+
<mat-select *ngIf="installations.length > 1; else singleInstall" [ngModel]="(installationsService.currentInstallation.asObservable() | async)?.id || 1"
63+
(ngModelChange)="installationsService.setInstallation($event)">
64+
<mat-option [value]="1">Enterprise</mat-option>
65+
@for (installation of installationsService.getInstallations() | async; track installation.id) {
66+
<mat-option [value]="installation.id">{{ installation.account?.login }}</mat-option>
67+
}
68+
</mat-select>
69+
<ng-template #singleInstall>
70+
<span>{{ installations[0]?.account?.login }}</span>
71+
</ng-template>
72+
</h1>
73+
</ng-container>
6774
</div>
6875
<span class="spacer"></span>
6976
</mat-toolbar>

frontend/src/app/services/api/setup.service.ts

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -55,11 +55,7 @@ export class SetupService {
5555
}
5656

5757
setupDB(request: { // should be url or fields
58-
host?: string;
59-
port?: number;
60-
username?: string;
61-
password?: string;
62-
url?: string;
58+
uri: string;
6359
}) {
6460
return this.http.post(`${this.apiUrl}/db`, request);
6561
}

0 commit comments

Comments
 (0)