From 4a44820d8e1bf530e8763709d018f3ae09d5b431 Mon Sep 17 00:00:00 2001 From: delivan Date: Tue, 29 Aug 2023 13:22:55 +0900 Subject: [PATCH] Add api for getting native mainnet, testnet chain infos --- pages/api/native-chains.ts | 60 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 pages/api/native-chains.ts diff --git a/pages/api/native-chains.ts b/pages/api/native-chains.ts new file mode 100644 index 000000000..a4a3d0c7b --- /dev/null +++ b/pages/api/native-chains.ts @@ -0,0 +1,60 @@ +// Next.js API route support: https://nextjs.org/docs/api-routes/introduction +import type { NextApiRequest, NextApiResponse } from "next"; + +import path from "path"; +import { promises as fs } from "fs"; +import { ChainInfo } from "@keplr-wallet/types"; +import Cors from "cors"; +import { + nativeMainnetChainIdentifiers, + nativeTestnetChainIdentifiers, +} from "../../src/constants"; +import { ChainIdHelper } from "@keplr-wallet/cosmos"; + +type Data = { + mainnetChains: ChainInfo[]; + testnetChains: ChainInfo[]; +}; + +const cors = Cors({ + methods: ["GET"], +}); + +export default async function ( + req: NextApiRequest, + res: NextApiResponse, +) { + await new Promise((resolve, reject) => { + cors(req, res, (result: any) => { + if (result instanceof Error) { + return reject(result); + } + + return resolve(result); + }); + }); + + const jsonDirectory = path.join(process.cwd(), "cosmos"); + + const fetchChains = (await fs.readdir(jsonDirectory)).map((fileName) => + fs.readFile(`${jsonDirectory}/${fileName}`, "utf8"), + ); + + const chainInfos: ChainInfo[] = (await Promise.all(fetchChains)).map( + (chainInfo) => JSON.parse(chainInfo), + ); + + //Return the content of the data file in json format + res.status(200).json({ + mainnetChains: chainInfos.filter((chainInfo) => + nativeMainnetChainIdentifiers.includes( + ChainIdHelper.parse(chainInfo.chainId).identifier, + ), + ), + testnetChains: chainInfos.filter((chainInfo) => + nativeTestnetChainIdentifiers.includes( + ChainIdHelper.parse(chainInfo.chainId).identifier, + ), + ), + }); +}