server/database/entities/Instance.ts

51 lines
1.4 KiB
TypeScript
Raw Normal View History

2024-04-10 07:13:13 +02:00
import type * as Lysand from "lysand-types";
import { db } from "~drizzle/db";
import { Instances } from "~drizzle/schema";
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 (url: string) => {
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 db.query.instance.findFirst({
where: (instance, { eq }) => eq(instance.baseUrl, host),
2024-04-07 07:30:49 +02:00
});
if (found) return found;
console.log(`Fetching instance metadata for ${origin}`);
2024-04-07 07:30:49 +02:00
// 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 db
.insert(Instances)
.values({
baseUrl: host,
name: metadata.name,
version: metadata.version,
logo: metadata.logo,
})
.returning()
)[0];
};