/ src / pages / api / single-token.ts
single-token.ts
 1  import { env } from "@/env.mjs";
 2  import type { NextApiRequest, NextApiResponse } from "next";
 3  
 4  interface HistoryData {
 5    date: number;
 6    rate: number;
 7    volume: number;
 8    cap: number;
 9  }
10  
11  interface SingleTokenData {
12    history: HistoryData[];
13  }
14  
15  interface RequestBody {
16    currency: string;
17    code: string;
18    start: number;
19    end: number;
20    meta: boolean;
21  }
22  
23  export default async function handler(
24    req: NextApiRequest,
25    res: NextApiResponse<SingleTokenData>,
26  ) {
27    if (req.method !== "POST") {
28      return res.status(405).json({ history: [] });
29    }
30  
31    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
32    const { currency, code, start, end } = req.body as RequestBody;
33  
34    const requestBody = {
35      currency: currency,
36      code: code,
37      start: start,
38      end: end,
39      meta: false,
40    };
41  
42    const response = await fetch(
43      `https://api.livecoinwatch.com/coins/single/history`,
44      {
45        method: "POST",
46        headers: {
47          "Content-Type": "application/json",
48          "x-api-key": env.LIVECOINWATCH_API_KEY,
49        },
50        body: JSON.stringify(requestBody),
51      },
52    );
53  
54    if (!response.ok) {
55      return res.status(response.status).json({ history: [] });
56    }
57  
58    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
59    const data: SingleTokenData = await response.json();
60    res.status(200).json(data);
61  }