feat: adicionar construtor de dashboards e api de métricas
This commit is contained in:
parent
c2acd65764
commit
741f1d7f9c
14 changed files with 4356 additions and 9 deletions
77
src/app/api/export/pdf/route.ts
Normal file
77
src/app/api/export/pdf/route.ts
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
import { NextResponse } from "next/server"
|
||||
|
||||
export const runtime = "nodejs"
|
||||
|
||||
type ExportRequest = {
|
||||
url?: string
|
||||
width?: number
|
||||
height?: number
|
||||
format?: "pdf" | "png"
|
||||
waitForSelector?: string
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
let payload: ExportRequest
|
||||
try {
|
||||
payload = await request.json()
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: "Payload inválido" }, { status: 400 })
|
||||
}
|
||||
|
||||
if (!payload.url) {
|
||||
return NextResponse.json({ error: "URL obrigatória" }, { status: 400 })
|
||||
}
|
||||
|
||||
const { chromium } = await import("playwright")
|
||||
const width = payload.width ?? 1920
|
||||
const height = payload.height ?? 1080
|
||||
const format = payload.format ?? "pdf"
|
||||
const waitForSelector = payload.waitForSelector ?? "[data-dashboard-ready='true']"
|
||||
|
||||
let browser: Awaited<ReturnType<typeof chromium.launch>> | null = null
|
||||
|
||||
try {
|
||||
browser = await chromium.launch()
|
||||
const page = await browser.newPage({ viewport: { width, height } })
|
||||
await page.goto(payload.url, { waitUntil: "networkidle" })
|
||||
if (waitForSelector) {
|
||||
try {
|
||||
await page.waitForSelector(waitForSelector, { timeout: 15000 })
|
||||
} catch (error) {
|
||||
console.warn("waitForSelector timeout", error)
|
||||
}
|
||||
}
|
||||
|
||||
if (format === "pdf") {
|
||||
const pdf = await page.pdf({
|
||||
width: `${width}px`,
|
||||
height: `${height}px`,
|
||||
printBackground: true,
|
||||
pageRanges: "1",
|
||||
})
|
||||
return new NextResponse(pdf, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/pdf",
|
||||
"Content-Disposition": "attachment; filename=dashboard.pdf",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const screenshot = await page.screenshot({ type: "png", fullPage: true })
|
||||
return new NextResponse(screenshot, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "image/png",
|
||||
"Content-Disposition": "attachment; filename=dashboard.png",
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
console.error("Failed to export dashboard", error)
|
||||
return NextResponse.json({ error: "Falha ao exportar o dashboard" }, { status: 500 })
|
||||
} finally {
|
||||
if (browser) {
|
||||
await browser.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue