Skip to content

Commit

Permalink
fix: Integrate maintenance mode with current middleware (#14571)
Browse files Browse the repository at this point in the history
* fix: API v1 maintenance mode

* Removed old middleware

* Refactor to follow same pattern as other middleware

* Added missing import
  • Loading branch information
keithwillcode committed Apr 13, 2024
1 parent 98f94ea commit ac3d7c9
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 9 deletions.
@@ -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 <T = unknown>(key: string): Promise<T | undefined> => {
try {
Expand All @@ -11,12 +11,13 @@ const safeGet = async <T = unknown>(key: string): Promise<T | undefined> => {

export const config = { matcher: "/:path*" };

export async function middleware() {
export const checkIsInMaintenanceMode: NextMiddleware = async (req, res, next) => {
const isInMaintenanceMode = await safeGet<boolean>("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();
};
3 changes: 3 additions & 0 deletions apps/api/v1/lib/helpers/withMiddleware.ts
Expand Up @@ -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,
Expand All @@ -24,6 +25,7 @@ const middleware = {
HTTP_POST,
HTTP_DELETE,
addRequestId,
checkIsInMaintenanceMode,
verifyApiKey,
rateLimitApiKey,
extendRequest,
Expand All @@ -36,6 +38,7 @@ type Middleware = keyof typeof middleware;

const middlewareOrder = [
// The order here, determines the order of execution
"checkIsInMaintenanceMode",
"extendRequest",
"captureErrors",
"verifyApiKey",
Expand Down

0 comments on commit ac3d7c9

Please sign in to comment.