server/database/entities/Instance.ts

50 lines
1.3 KiB
TypeScript
Raw Normal View History

import type { Instance } from "@prisma/client";
import { client } from "~database/datasource";
2024-04-10 07:13:13 +02:00
import type * as Lysand from "lysand-types";
2023-09-12 22:48:10 +02:00
2023-09-28 20:19:21 +02:00
/**
* Represents an instance in the database.
*/
2023-09-12 22:48:10 +02:00
/**
* Adds an instance to the database if it doesn't already exist.
* @param url
* @returns Either the database instance if it already exists, or a newly created instance.
*/
export const addInstanceIfNotExists = async (
2024-04-07 07:30:49 +02:00
url: string,
): Promise<Instance> => {
2024-04-07 07:30:49 +02:00
const origin = new URL(url).origin;
2024-04-10 07:13:13 +02:00
const host = new URL(url).host;
2024-04-07 07:30:49 +02:00
const found = await client.instance.findFirst({
where: {
2024-04-10 07:13:13 +02:00
base_url: host,
2024-04-07 07:30:49 +02:00
},
});
if (found) return found;
// Fetch the instance configuration
2024-04-10 07:13:13 +02:00
const metadata = (await fetch(new URL("/.well-known/lysand", origin)).then(
(res) => res.json(),
)) as Lysand.ServerMetadata;
2024-04-07 07:30:49 +02:00
if (metadata.type !== "ServerMetadata") {
2024-04-10 07:13:13 +02:00
throw new Error("Invalid instance metadata (wrong type)");
2024-04-07 07:30:49 +02:00
}
if (!(metadata.name && metadata.version)) {
2024-04-10 07:13:13 +02:00
throw new Error("Invalid instance metadata (missing name or version)");
2024-04-07 07:30:49 +02:00
}
return await client.instance.create({
data: {
2024-04-10 07:13:13 +02:00
base_url: host,
2024-04-07 07:30:49 +02:00
name: metadata.name,
version: metadata.version,
logo: metadata.logo,
},
});
};