Skip to content

Commit 6846606

Browse files
committed
refactor(utils): Consolidate reload function into utils module
1 parent 2bd132d commit 6846606

File tree

3 files changed

+68
-71
lines changed

3 files changed

+68
-71
lines changed

src/app.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,12 @@ import {
99
import ejs from 'ejs';
1010
import cors from 'cors';
1111
import express from 'express';
12+
import { reload } from './utils';
1213
import flash from 'connect-flash';
1314
import { router } from './router';
1415
import { appConfig } from './config';
1516
import compression from 'compression';
1617
import expressLayouts from 'express-ejs-layouts';
17-
import { reload } from './reload';
1818

1919
const app = express();
2020

src/reload.ts

Lines changed: 0 additions & 67 deletions
This file was deleted.

src/utils.ts

Lines changed: 67 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,16 @@ import jwt from 'jsonwebtoken';
77
import dayjsModule from 'dayjs';
88
import { Redis } from 'ioredis';
99
import { logger } from './logger';
10-
import fs from 'node:fs/promises';
11-
import { Request } from 'express';
10+
import fsp from 'node:fs/promises';
11+
import fs from 'node:fs';
1212
import utc from 'dayjs/plugin/utc';
1313
import nodemailer from 'nodemailer';
1414
import { db, redis } from './db/db';
1515
import { Queue, Worker, Job } from 'bullmq';
1616
import timezone from 'dayjs/plugin/timezone';
1717
import { appConfig, emailConfig, oauthConfig, sessionConfig } from './config';
1818
import { GithubUserEmail, GitHubOauthToken, ApiKeyPayload, User } from './types';
19+
import { Application, Request, Response, NextFunction } from 'express';
1920

2021
export function dayjs(date: string | Date = new Date()) {
2122
dayjsModule.extend(utc);
@@ -234,7 +235,7 @@ export async function sendGeneralEmail({
234235
message: string;
235236
}) {
236237
try {
237-
const templateContent = await fs.readFile(
238+
const templateContent = await fsp.readFile(
238239
path.resolve(path.join(process.cwd(), 'src', 'views', 'emails', 'general.html')),
239240
'utf-8',
240241
);
@@ -284,3 +285,66 @@ export const modifyUserSessionById = async (
284285
logger.error('No session found for user ID:', userId);
285286
return null;
286287
};
288+
289+
export function reload({
290+
app,
291+
watch,
292+
options = {},
293+
}: {
294+
app: Application;
295+
watch: { path: string; extensions: string[] }[];
296+
options?: { pollInterval?: number; quiet?: boolean };
297+
}): void {
298+
if (appConfig.env !== 'development') return;
299+
300+
const pollInterval = options.pollInterval || 50;
301+
const quiet = options.quiet || false;
302+
let changeDetected = false;
303+
304+
watch.forEach(({ path: dir, extensions }) => {
305+
const extensionsSet = new Set(extensions);
306+
fs.watch(dir, { recursive: true }, (_: fs.WatchEventType, filename: string | null) => {
307+
if (filename && extensionsSet.has(filename.slice(filename.lastIndexOf('.')))) {
308+
if (!quiet) logger.info('[reload] File changed: %s', filename);
309+
changeDetected = true;
310+
}
311+
});
312+
});
313+
314+
app.get('/wait-for-reload', (req: Request, res: Response) => {
315+
const timer = setInterval(() => {
316+
if (changeDetected) {
317+
changeDetected = false;
318+
clearInterval(timer);
319+
res.send();
320+
}
321+
}, pollInterval);
322+
323+
req.on('close', () => clearInterval(timer));
324+
});
325+
326+
const clientScript = `
327+
<script>
328+
(async function poll() {
329+
try {
330+
await fetch('/wait-for-reload');
331+
location.reload();
332+
} catch {
333+
location.reload();
334+
}
335+
})();
336+
</script>\n\t`;
337+
338+
app.use((req: Request, res: Response, next: NextFunction) => {
339+
const originalSend = res.send.bind(res);
340+
341+
res.send = function (body: any): Response {
342+
if (typeof body === 'string' && body.includes('</head>')) {
343+
body = body.replace('</head>', clientScript + '</head>');
344+
}
345+
return originalSend(body);
346+
};
347+
348+
next();
349+
});
350+
}

0 commit comments

Comments
 (0)