updated /organisation/create route. creates member and ensures no duplicated slugs

This commit is contained in:
Oliver Bryan
2025-12-29 04:44:37 +00:00
parent 542efbd240
commit 1b68d82565

View File

@@ -1,23 +1,37 @@
import type { BunRequest } from "bun"; import type { AuthedRequest } from "../../auth/middleware";
import { createOrganisation } from "../../db/queries"; import { createOrganisationWithOwner, getOrganisationBySlug } from "../../db/queries";
// /organisation/create?name=Org%20Name&slug=org-name&description=Optional%20description // /organisation/create?name=Org%20Name&slug=org-name&userId=1&description=Optional%20description
export default async function organisationCreate(req: BunRequest) { export default async function organisationCreate(req: AuthedRequest) {
const url = new URL(req.url); const url = new URL(req.url);
const name = url.searchParams.get("name"); const name = url.searchParams.get("name");
const slug = url.searchParams.get("slug"); const slug = url.searchParams.get("slug");
const userId = url.searchParams.get("userId");
const description = url.searchParams.get("description") || undefined; const description = url.searchParams.get("description") || undefined;
if (!name || !slug) { if (!name || !slug || !userId) {
return new Response(`missing parameters: ${!name ? "name " : ""}${!slug ? "slug" : ""}`, { return new Response(
status: 400, `missing parameters: ${!name ? "name " : ""}${!slug ? "slug " : ""}${!userId ? "userId" : ""}`,
}); { status: 400 },
);
} }
// Check if organisation with slug already exists const userIdNumber = Number(userId);
// TODO: Add this check when we have a getOrganisationBySlug function if (!Number.isInteger(userIdNumber)) {
return new Response("userId must be an integer", { status: 400 });
}
const organisation = await createOrganisation(name, slug, description); // users can only create organisations for themselves (userId cannot be spoofed)
if (req.userId !== userIdNumber) {
return new Response("access denied: you can only create organisations for yourself", { status: 403 });
}
const existingOrganisation = await getOrganisationBySlug(slug);
if (existingOrganisation) {
return new Response(`organisation with slug "${slug}" already exists`, { status: 409 });
}
const organisation = await createOrganisationWithOwner(name, slug, userIdNumber, description);
return Response.json(organisation); return Response.json(organisation);
} }