toot-script-condivisione-su.../src/pages/api/instances.ts

77 lines
1.9 KiB
TypeScript
Raw Normal View History

2023-03-18 02:11:18 +01:00
/*!
2023-09-02 16:17:15 +02:00
* This file is part of ShareFedi
* https://github.com/kytta/share2fedi
*
* SPDX-FileCopyrightText: © 2023 Nikita Karamov <me@kytta.dev>
* SPDX-License-Identifier: AGPL-3.0-only
2023-03-18 02:11:18 +01:00
*/
2023-03-18 04:14:03 +01:00
import type { APIRoute } from "astro";
2023-03-27 19:22:41 +02:00
import { FediverseProject } from "@scripts/constants";
2023-03-18 04:14:03 +01:00
interface ProjectInstance {
2023-03-18 04:14:03 +01:00
domain: string;
score: number;
active_users_monthly: number;
2023-08-26 17:03:14 +02:00
total_users: number;
2023-03-18 04:14:03 +01:00
}
const PROJECTS = Object.values(FediverseProject);
export const fetchInstances = async (
projectId: string,
): Promise<ProjectInstance[]> => {
const response = await fetch("https://api.fediverse.observer/", {
headers: {
Accept: "*/*",
"Accept-Language": "en;q=1.0",
"Content-Type": "application/json",
},
referrer: "https://api.fediverse.observer/",
2023-08-26 17:03:14 +02:00
body: JSON.stringify({
query: `{nodes(status:"UP",softwarename:"${projectId}"){domain score active_users_monthly total_users}}`,
}),
method: "POST",
});
const json = await response.json();
const instances: ProjectInstance[] = json.data.nodes;
return instances.filter(
2023-08-26 17:03:14 +02:00
(instance) =>
instance.score > 90 &&
instance.total_users >= instance.active_users_monthly,
);
};
export const get: APIRoute = async () => {
try {
const response = await Promise.all(
PROJECTS.map((projectId) => fetchInstances(projectId)),
);
const instances = response.flat();
instances.sort((a, b) => {
return b.active_users_monthly - a.active_users_monthly;
});
return new Response(
2023-03-18 04:14:03 +01:00
JSON.stringify(
instances
.slice(0, 200)
.map((instance: ProjectInstance) => instance.domain),
2023-03-18 04:14:03 +01:00
),
{
headers: {
2023-08-30 13:31:31 +02:00
"Cache-Control": "public, s-maxage=86400, max-age=604800",
"Content-Type": "application/json",
},
},
);
} catch (error) {
console.error("Could not fetch instances:", error);
return new Response(JSON.stringify([]), {
headers: {
"Content-Type": "application/json",
},
});
}
};