rudeshark.net/packages/backend/src/server/api/endpoints/patrons.ts

59 lines
1.5 KiB
TypeScript
Raw Normal View History

2023-01-13 05:40:33 +01:00
import define from "../define.js";
2023-06-08 22:19:46 +02:00
import { redisClient } from "@/db/redis.js";
import * as fs from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname } from "node:path";
const _filename = fileURLToPath(import.meta.url);
const _dirname = dirname(_filename);
2022-11-19 08:54:50 +01:00
export const meta = {
2023-01-13 05:40:33 +01:00
tags: ["meta"],
2023-07-15 23:21:17 +02:00
description: "Get Firefish patrons",
2022-11-19 08:54:50 +01:00
requireCredential: false,
requireCredentialPrivateMode: false,
} as const;
export const paramDef = {
2023-01-13 05:40:33 +01:00
type: "object",
properties: {
forceUpdate: { type: "boolean", default: false },
},
2022-11-19 08:54:50 +01:00
required: [],
} as const;
export default define(meta, paramDef, async (ps) => {
2022-11-19 08:54:50 +01:00
let patrons;
2023-06-08 22:19:46 +02:00
const cachedPatrons = await redisClient.get("patrons");
if (!ps.forceUpdate && cachedPatrons) {
2023-06-08 22:19:46 +02:00
patrons = JSON.parse(cachedPatrons);
2023-06-12 06:57:20 +02:00
} else {
2023-07-02 09:16:01 +02:00
AbortSignal.timeout ??= function timeout(ms) {
2023-07-03 08:08:33 +02:00
const ctrl = new AbortController();
setTimeout(() => ctrl.abort(), ms);
return ctrl.signal;
};
2023-07-02 09:16:01 +02:00
2023-06-08 22:19:46 +02:00
patrons = await fetch(
2023-07-15 23:21:17 +02:00
"https://codeberg.org/firefish/firefish/raw/branch/develop/patrons.json",
2023-07-03 08:08:33 +02:00
{ signal: AbortSignal.timeout(2000) },
)
.then((response) => response.json())
.catch(() => {
const staticPatrons = JSON.parse(
2023-07-06 21:47:33 +02:00
fs.readFileSync(
`${_dirname}/../../../../../../patrons.json`,
"utf-8",
),
);
patrons = cachedPatrons ? JSON.parse(cachedPatrons) : staticPatrons;
});
2023-06-08 22:19:46 +02:00
await redisClient.set("patrons", JSON.stringify(patrons), "EX", 3600);
}
return {
patrons: patrons["patrons"],
sponsors: patrons["sponsors"],
};
2022-11-19 08:54:50 +01:00
});