Files
randomgif/index.js
T
Simon Gruber dfb258c90c Updates
2026-05-11 08:15:49 +02:00

62 lines
1.8 KiB
JavaScript

const http = require("http");
const axios = require("axios");
// Configuration
const host = process.env.HOST || "0.0.0.0";
const port = process.env.PORT || 8080;
const GIPHY_API_KEY = process.env.GIPHY_API_KEY;
const PROXY_SECRET = process.env.PROXY_SECRET || "gif";
function catchError(res, error) {
console.error("An error occurred:", error.message);
res.writeHead(500);
res.end(JSON.stringify({ error: "Internal Server Error" }));
}
const requestListener = function (clientReq, clientRes) {
const parts = clientReq.url?.split("/").filter(Boolean) || [];
const providedSecret = parts[0];
const tag = parts[1] || "";
if (providedSecret !== PROXY_SECRET) {
console.warn(`Unauthorized access: Invalid secret`);
clientRes.writeHead(403);
clientRes.end();
return;
}
if (!GIPHY_API_KEY) {
console.error("GIPHY_API_KEY is not configured.");
clientRes.writeHead(500);
clientRes.end();
return;
}
const apiUrl = `https://api.giphy.com/v1/gifs/random?api_key=${GIPHY_API_KEY}&rating=pg-13${tag ? `&tag=${tag}` : ""}`;
axios
.get(apiUrl)
.then((apiRes) => {
const gifUrl = apiRes?.data?.data?.images?.original?.url;
if (gifUrl) {
console.log(`Success: Found GIF for '${tag}'`);
clientRes.setHeader("Content-Type", "application/json");
clientRes.writeHead(200);
clientRes.end(JSON.stringify({ url: gifUrl }));
} else {
console.log(`Notice: No GIF found for topic '${tag}'`);
clientRes.writeHead(404);
clientRes.end(JSON.stringify({ error: "No GIF found" }));
}
})
.catch((error) => {
catchError(clientRes, error);
});
};
const server = http.createServer(requestListener);
server.listen(port, host, () => {
console.log(`Server is running on http://${host}:${port}`);
});