From ac3d7c9fae221d24dc44ac211b1dc45f2a33805a Mon Sep 17 00:00:00 2001 From: Keith Williams Date: Sat, 13 Apr 2024 16:27:22 -0300 Subject: [PATCH] fix: Integrate maintenance mode with current middleware (#14571) * fix: API v1 maintenance mode * Removed old middleware * Refactor to follow same pattern as other middleware * Added missing import --- .../helpers/checkIsInMaintenanceMode.ts} | 19 ++++++++++--------- apps/api/v1/lib/helpers/withMiddleware.ts | 3 +++ 2 files changed, 13 insertions(+), 9 deletions(-) rename apps/api/v1/{middleware.ts => lib/helpers/checkIsInMaintenanceMode.ts} (51%) diff --git a/apps/api/v1/middleware.ts b/apps/api/v1/lib/helpers/checkIsInMaintenanceMode.ts similarity index 51% rename from apps/api/v1/middleware.ts rename to apps/api/v1/lib/helpers/checkIsInMaintenanceMode.ts index 126c6f7d1a..8f2f0879b3 100644 --- a/apps/api/v1/middleware.ts +++ b/apps/api/v1/lib/helpers/checkIsInMaintenanceMode.ts @@ -1,5 +1,5 @@ import { get } from "@vercel/edge-config"; -import { NextResponse } from "next/server"; +import type { NextMiddleware } from "next-api-middleware"; const safeGet = async (key: string): Promise => { try { @@ -11,12 +11,13 @@ const safeGet = async (key: string): Promise => { export const config = { matcher: "/:path*" }; -export async function middleware() { +export const checkIsInMaintenanceMode: NextMiddleware = async (req, res, next) => { const isInMaintenanceMode = await safeGet("isInMaintenanceMode"); - if (!isInMaintenanceMode) return NextResponse.next(); - // If is in maintenance mode, return a 503 status code - return NextResponse.json( - { message: "API is currently under maintenance. Please try again at a later time." }, - { status: 503 } - ); -} + if (isInMaintenanceMode) { + return res + .status(503) + .json({ message: "API is currently under maintenance. Please try again at a later time." }); + } + + await next(); +}; diff --git a/apps/api/v1/lib/helpers/withMiddleware.ts b/apps/api/v1/lib/helpers/withMiddleware.ts index b0d0922afb..95b8984ee1 100644 --- a/apps/api/v1/lib/helpers/withMiddleware.ts +++ b/apps/api/v1/lib/helpers/withMiddleware.ts @@ -2,6 +2,7 @@ import { label } from "next-api-middleware"; import { addRequestId } from "./addRequestid"; import { captureErrors } from "./captureErrors"; +import { checkIsInMaintenanceMode } from "./checkIsInMaintenanceMode"; import { extendRequest } from "./extendRequest"; import { HTTP_POST, @@ -24,6 +25,7 @@ const middleware = { HTTP_POST, HTTP_DELETE, addRequestId, + checkIsInMaintenanceMode, verifyApiKey, rateLimitApiKey, extendRequest, @@ -36,6 +38,7 @@ type Middleware = keyof typeof middleware; const middlewareOrder = [ // The order here, determines the order of execution + "checkIsInMaintenanceMode", "extendRequest", "captureErrors", "verifyApiKey",