Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: add health check for backend connection in middleware #185

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/hooks.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,24 @@ const configureClientMiddleware: Handle = async ({ event, resolve }) => {
if (!event.locals.backendUrl || !event.locals.apiKey) {
throw redirect(307, '/connect');
}

let hasConnection;

try {
await fetch(event.locals.backendUrl + '/api/v1/health')
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Address linting issues

  1. Use template literals instead of string concatenation
  2. Prefix unused error parameters with underscore

Apply these changes:

-			await fetch(event.locals.backendUrl + '/api/v1/health')
+			await fetch(`${event.locals.backendUrl}/api/v1/health`)
-				.catch((error) => {
+				.catch((_error) => {
-		} catch (error) {
+		} catch (_error) {

Also applies to: 37-37, 40-40

🧰 Tools
🪛 Biome (1.9.4)

[error] 33-33: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)

.then(() => {
hasConnection = true;
})
.catch(() => {
hasConnection = false;
});
} catch {
hasConnection = false;
}

if (!hasConnection) {
throw redirect(307, '/connect');
}
Comment on lines +44 to +46
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Consider implementing redirect debouncing

While the redirect logic is correct, frequent health check failures could lead to rapid redirects, potentially causing a poor user experience. Consider implementing a grace period before redirecting.

// Add at the top of the file
let lastRedirectTime = 0;
const REDIRECT_COOLDOWN = 5000; // 5 seconds

// Replace the redirect logic
if (!hasConnection) {
  const now = Date.now();
  if (now - lastRedirectTime > REDIRECT_COOLDOWN) {
    lastRedirectTime = now;
    throw redirect(307, '/connect');
  }
  // If within cooldown period, continue with degraded service
  console.warn('Backend connection failed but within redirect cooldown period');
}

}

return resolve(event);
Expand Down
Loading