fix(SW-449): dateFormat middleware

This commit is contained in:
Pontus Dreij
2024-11-13 08:57:14 +01:00
parent cf8585a3df
commit a16062a705
2 changed files with 41 additions and 0 deletions

View File

@@ -8,6 +8,7 @@ import * as cmsContent from "@/middlewares/cmsContent"
import * as currentWebLogin from "@/middlewares/currentWebLogin"
import * as currentWebLoginEmail from "@/middlewares/currentWebLoginEmail"
import * as currentWebLogout from "@/middlewares/currentWebLogout"
import * as dateFormat from "@/middlewares/dateFormat"
import * as handleAuth from "@/middlewares/handleAuth"
import * as myPages from "@/middlewares/myPages"
import { getDefaultRequestHeaders } from "@/middlewares/utils"
@@ -52,6 +53,7 @@ export const middleware: NextMiddleware = async (request, event) => {
webView,
bookingFlow,
cmsContent,
dateFormat,
]
try {

39
middlewares/dateFormat.ts Normal file
View File

@@ -0,0 +1,39 @@
import { NextMiddleware, NextResponse } from "next/server"
import { MiddlewareMatcher } from "@/types/middleware"
/*
Middleware function to normalize date formats to support
YYYY-MM-D and YYYY-MM-DD since the current web uses YYYY-MM-D
in the URL as parameters (toDate and fromDate)
*/
export const middleware: NextMiddleware = (request) => {
const url = request.nextUrl.clone()
const { searchParams } = url
function normalizeDate(date: string): string {
const datePattern = /^\d{4}-\d{1,2}-\d{1,2}$/
if (datePattern.test(date)) {
const [year, month, day] = date.split("-").map(Number)
return `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`
}
return date
}
if (searchParams.has("fromDate")) {
const fromDate = searchParams.get("fromDate")!
searchParams.set("fromDate", normalizeDate(fromDate))
}
if (searchParams.has("toDate")) {
const toDate = searchParams.get("toDate")!
searchParams.set("toDate", normalizeDate(toDate))
}
return NextResponse.rewrite(url)
}
export const matcher: MiddlewareMatcher = (request) => {
const { searchParams } = request.nextUrl
return searchParams.has("fromDate") || searchParams.has("toDate")
}