From a7655b63484860deef8173bb8336c68423968f03 Mon Sep 17 00:00:00 2001 From: Manuel <30572287+manuel-rw@users.noreply.github.com> Date: Sun, 8 Oct 2023 11:45:30 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Database=20error=20with=20readon?= =?UTF-8?q?ly=20mappings=20(#1420)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 🐛 Database error with readonly mappings * ♻️ PR feedback --- src/middleware.ts | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/src/middleware.ts b/src/middleware.ts index fe1b18311..a5e0b2125 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -1,3 +1,5 @@ +import Consola from 'consola'; +import fs from 'fs/promises'; import { NextRequest, NextResponse } from 'next/server'; import { env } from 'process'; @@ -34,13 +36,32 @@ export async function middleware(req: NextRequest) { return NextResponse.next(); } - // is only called from when there were no users in the database in this session (Since the app started) - cachedUserCount = await client.user.count.query(); - // Do not redirect if there are users in the database - if (cachedUserCount > 0) { + if (!(await shouldRedirectToOnboard())) { return NextResponse.next(); } return NextResponse.redirect(getUrl(req) + '/onboard'); } + +const shouldRedirectToOnboard = async (): Promise => { + const cacheAndGetUserCount = async () => { + cachedUserCount = await client.user.count.query(); + return cachedUserCount === 0; + } + + if (!env.DATABASE_URL?.startsWith('file:')) { + return await cacheAndGetUserCount(); + } + + const fileUri = env.DATABASE_URL.substring(4); + try { + await fs.access(fileUri, fs.constants.W_OK); + return await cacheAndGetUserCount(); + } catch { + Consola.warn( + `detected that the path ${fileUri} was not readable. Showing onboarding page for setup...` + ); + return true; + } +};