프론트엔드 웹/Next

Next.js API Router로 Chart.js 이미지 리턴하기

세리둥절 2023. 5. 16. 09:57
반응형
import { NextResponse } from "next/server";
import { createCanvas } from 'canvas';
import Chart, { ChartConfiguration } from 'chart.js/auto';


export async function GET() {
    const data = { 
        pokemon: {
            name: '꼬부기'
        }
    }
    return NextResponse.json({ data });
}
    


export async function POST(request: Request, response: Response) {
    const data = await request.json();
    console.log('req', data);

    const canvas = createCanvas(800, 600);
    const ctx: any = canvas.getContext('2d');

    const chartConfig: ChartConfiguration = {
        type: 'bar',
        data: {
          labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
          datasets: [
            {
                label: '# of Votes',
                data: [12, 19, 3, 5, 2, 3]
            }
          ]
        },
        options: {
          responsive: false,
          plugins: {
            legend: {
              position: 'top'
            }
          }
        }
    };
    const chart = new Chart(ctx, chartConfig);
    const imageData = canvas.toBuffer();
    
    return new NextResponse(imageData, {
        status: 200,
        headers: { 'Content-Type': 'image/png' },
    })
}

 

 

 


 

 

import { NextResponse } from "next/server";
import { NextApiHandler } from 'next';
import { createCanvas } from 'canvas';
import Chart, { ChartConfiguration } from 'chart.js/auto';


const handler: NextApiHandler = async (req, res) => {
    if (req.method === 'GET') {
        const data = { 
            pokemon: {
                name: '꼬부기'
            }
        }
        res.status(200).json({ data: data })
    } 

    if (req.method === 'POST') {
        const canvas = createCanvas(800, 600);
        const ctx: any = canvas.getContext('2d');

        const chartConfig: ChartConfiguration = {
            type: 'bar',
            data: {
            labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
            datasets: [
                {
                    label: '# of Votes',
                    data: [12, 19, 3, 5, 2, 3]
                }
            ]
            },
            options: {
            responsive: false,
            plugins: {
                legend: {
                position: 'top'
                }
            }
            }
        };
        const chart = new Chart(ctx, chartConfig);
        const imageData = canvas.toBuffer();
    
        res.writeHead(200, {
            'Content-Type': 'image/png',
          });
        res.end(imageData);
    }
};

export default handler;

 

반응형