import Fastify from "fastify"; import helmet from "@fastify/helmet"; import rateLimit from "@fastify/rate-limit"; import cors from "@fastify/cors"; import { checkIp } from "./checkIp.js"; const fastify = Fastify(); await fastify.register(helmet); await fastify.register(rateLimit, { max: (request) => (request.headers["x-api-key"] ? 100 : 1), timeWindow: "1 second", keyGenerator: (request) => request.headers["x-api-key"] || request.ip, addHeaders: { "x-ratelimit-limit": true, "x-ratelimit-remaining": true, "x-ratelimit-reset": true, }, }); await fastify.register(cors); fastify.get( "/api/ip/:ip", { schema: { params: { type: "object", properties: { ip: { type: "string", format: "ipv4" }, }, required: ["ip"], }, }, }, async function handler(request, reply) { try { const datacenter = checkIp(request.params.ip); reply.header("Content-Type", "application/json"); reply.send({ datacenter }); } catch (err) { reply.code(500).send({ error: "Internal Server Error" }); } } ); try { await fastify.listen({ port: 3000 }); } catch (err) { fastify.log.error(err); process.exit(1); }