Linked backend data to detectors' meshes.
This commit is contained in:
71
frontend/app/api/update-alert/[id]/route.ts
Normal file
71
frontend/app/api/update-alert/[id]/route.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import { NextResponse, NextRequest } from 'next/server'
|
||||
import { getServerSession } from 'next-auth'
|
||||
import { authOptions } from '@/lib/auth'
|
||||
import { getToken } from 'next-auth/jwt'
|
||||
|
||||
export async function PATCH(req: NextRequest, context: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const session = await getServerSession(authOptions)
|
||||
const authHeader = req.headers.get('authorization') || req.headers.get('Authorization')
|
||||
const bearer = authHeader && authHeader.toLowerCase().startsWith('bearer ') ? authHeader.slice(7) : undefined
|
||||
const secret = process.env.NEXTAUTH_SECRET
|
||||
const token = await getToken({ req, secret }).catch(() => null)
|
||||
|
||||
let accessToken = session?.accessToken || bearer || (token as any)?.accessToken
|
||||
const refreshToken = session?.refreshToken || (token as any)?.refreshToken
|
||||
|
||||
if (!accessToken && refreshToken) {
|
||||
try {
|
||||
const refreshRes = await fetch(`${process.env.BACKEND_URL}/auth/refresh/`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ refresh: refreshToken }),
|
||||
})
|
||||
if (refreshRes.ok) {
|
||||
const refreshed = await refreshRes.json()
|
||||
accessToken = refreshed.access
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
if (!accessToken) {
|
||||
return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const backendUrl = process.env.BACKEND_URL
|
||||
if (!backendUrl) {
|
||||
return NextResponse.json({ success: false, error: 'BACKEND_URL is not configured' }, { status: 500 })
|
||||
}
|
||||
|
||||
const { id } = await context.params
|
||||
const res = await fetch(`${backendUrl}/account/update-alert/${id}/`, {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
cache: 'no-store',
|
||||
})
|
||||
|
||||
const text = await res.text()
|
||||
let payload: any
|
||||
try { payload = JSON.parse(text) } catch { payload = text }
|
||||
|
||||
if (!res.ok) {
|
||||
const err = typeof payload === 'string' ? payload : JSON.stringify(payload)
|
||||
return NextResponse.json({ success: false, error: `Backend update-alert error: ${err}` }, { status: res.status })
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true, data: payload })
|
||||
} catch (error) {
|
||||
console.error('Error updating alert status:', error)
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: 'Failed to update alert status',
|
||||
},
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user