Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

♻️ Migrate space settings mutations from tRPC to server actions (#2687)

Luke Vella02059ae6e591
diff --git a/apps/web/src/app/[locale]/(space)/settings/general/components/custom-branding-section.tsx b/apps/web/src/app/[locale]/(space)/settings/general/components/custom-branding-section.tsx
index 466b3fc7d..9db9d19ac 100644
--- a/apps/web/src/app/[locale]/(space)/settings/general/components/custom-branding-section.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/general/components/custom-branding-section.tsx
@@ -4,6 +4,7 @@ import { posthog } from "@rallly/posthog/client";
import { Button } from "@rallly/ui/button";
import { ColorPicker, parseColor } from "@rallly/ui/color-picker";
import { Field, FieldGroup, FieldLabel } from "@rallly/ui/field";
+import { toast } from "@rallly/ui/sonner";
import { Switch } from "@rallly/ui/switch";
import React from "react";
import {
@@ -16,10 +17,13 @@ import {
import { showPayWall, useIsFree } from "@/features/billing/client";
import { ProBadge } from "@/features/billing/components/pro-badge";
import { DEFAULT_PRIMARY_COLOR } from "@/features/branding/constants";
+import {
+ updateSpaceAction,
+ updateSpaceShowBrandingAction,
+} from "@/features/space/actions";
import { useSpace } from "@/features/space/client";
-import { Trans } from "@/i18n/client";
-import { useToastProgress } from "@/lib/use-toast-progress";
-import { trpc } from "@/trpc/client";
+import { Trans, useTranslation } from "@/i18n/client";
+import { useSafeAction } from "@/lib/safe-action/client";
export function CustomBrandingSection({
disabled = false,
@@ -28,42 +32,57 @@ export function CustomBrandingSection({
}) {
const { data: space } = useSpace();
const isFree = useIsFree();
- const toastProgress = useToastProgress();
- const utils = trpc.useUtils();
+ const { t } = useTranslation();
const currentColor = space.primaryColor ?? DEFAULT_PRIMARY_COLOR;
const [color, setColor] = React.useState(() => parseColor(currentColor));
const hexColor = color.toString("hex");
const isDirty = hexColor !== currentColor;
- const updateShowBranding = trpc.spaces.updateShowBranding.useMutation({
- onMutate: async ({ showBranding }) => {
- await utils.spaces.getCurrent.cancel();
- const previousData = utils.spaces.getCurrent.getData();
- utils.spaces.getCurrent.setData(undefined, (old) =>
- old ? { ...old, showBranding } : old,
- );
- return { previousData };
- },
- onError: (_err, _vars, context) => {
- utils.spaces.getCurrent.setData(undefined, context?.previousData);
- },
- });
+ const updateShowBranding = useSafeAction(updateSpaceShowBrandingAction);
+ const updateSpace = useSafeAction(updateSpaceAction);
+
+ // Holds the toggled value until the post-action router refresh
+ // delivers the updated space data, then defers to it.
+ const [pendingShowBranding, setPendingShowBranding] = React.useState<
+ boolean | null
+ >(null);
+ const showBranding = pendingShowBranding ?? space.showBranding;
- const updateSpace = trpc.spaces.update.useMutation();
+ React.useEffect(() => {
+ if (
+ pendingShowBranding !== null &&
+ space.showBranding === pendingShowBranding
+ ) {
+ setPendingShowBranding(null);
+ }
+ }, [space.showBranding, pendingShowBranding]);
- const handleToggle = (newChecked: boolean) => {
+ const handleToggle = async (newChecked: boolean) => {
if (isFree) {
posthog?.capture("branding_settings:paywall_trigger");
showPayWall();
return;
}
- toastProgress(updateShowBranding.mutateAsync({ showBranding: newChecked }));
+
+ setPendingShowBranding(newChecked);
+
+ const result = await updateShowBranding.executeAsync({
+ showBranding: newChecked,
+ });
+
+ if (result?.serverError || result?.validationErrors) {
+ setPendingShowBranding(null);
+ }
};
const handleSave = async () => {
const value = hexColor === DEFAULT_PRIMARY_COLOR ? null : hexColor;
- toastProgress(updateSpace.mutateAsync({ primaryColor: value }));
+ const result = await updateSpace.executeAsync({ primaryColor: value });
+
+ if (!result?.serverError && !result?.validationErrors) {
+ toast.success(t("saved", { defaultValue: "Saved" }));
+ }
};
return (
@@ -83,9 +102,9 @@ export function CustomBrandingSection({
<FieldGroup>
<Field orientation="horizontal">
<Switch
- checked={space.showBranding}
+ checked={showBranding}
onCheckedChange={handleToggle}
- disabled={disabled || updateShowBranding.isPending}
+ disabled={disabled || updateShowBranding.isExecuting}
/>
<FieldLabel>
<Trans
@@ -97,7 +116,7 @@ export function CustomBrandingSection({
</Field>
<div
className={
- !space.showBranding || disabled
+ !showBranding || disabled
? "pointer-events-none opacity-50"
: undefined
}
@@ -112,8 +131,8 @@ export function CustomBrandingSection({
<Field orientation="horizontal">
<Button
onClick={handleSave}
- disabled={!space.showBranding || !isDirty || disabled}
- loading={updateSpace.isPending}
+ disabled={!showBranding || !isDirty || disabled}
+ loading={updateSpace.isExecuting}
>
<Trans i18nKey="save" defaults="Save" />
</Button>
diff --git a/apps/web/src/app/[locale]/(space)/settings/general/components/space-settings-form.tsx b/apps/web/src/app/[locale]/(space)/settings/general/components/space-settings-form.tsx
index 0522860df..92c0a3759 100644
--- a/apps/web/src/app/[locale]/(space)/settings/general/components/space-settings-form.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/general/components/space-settings-form.tsx
@@ -18,10 +18,16 @@ import {
ImageUploadControl,
ImageUploadPreview,
} from "@/components/image-upload";
+import {
+ getSpaceImageUploadUrlAction,
+ removeSpaceImageAction,
+ updateSpaceAction,
+ updateSpaceImageAction,
+} from "@/features/space/actions";
import { SpaceIcon } from "@/features/space/components/space-icon";
import type { SpaceDTO } from "@/features/space/types";
import { Trans, useTranslation } from "@/i18n/client";
-import { trpc } from "@/trpc/client";
+import { useSafeAction } from "@/lib/safe-action/client";
const spaceSettingsSchema = z.object({
name: z
@@ -41,10 +47,9 @@ export function SpaceSettingsForm({
}: SpaceSettingsFormProps) {
const { t } = useTranslation();
- const updateSpace = trpc.spaces.update.useMutation();
- const getImageUploadUrl = trpc.spaces.getImageUploadUrl.useMutation();
- const updateImage = trpc.spaces.updateImage.useMutation();
- const removeImage = trpc.spaces.removeImage.useMutation();
+ const updateSpace = useSafeAction(updateSpaceAction);
+ const updateImage = useSafeAction(updateSpaceImageAction);
+ const removeImage = useSafeAction(removeSpaceImageAction);
const form = useForm({
resolver: zodResolver(spaceSettingsSchema),
@@ -53,37 +58,40 @@ export function SpaceSettingsForm({
},
});
+ const handleGetUploadUrl = async (input: {
+ fileType: "image/jpeg" | "image/png";
+ fileSize: number;
+ }) => {
+ const result = await getSpaceImageUploadUrlAction(input);
+
+ if (!result?.data) {
+ throw new Error("Failed to get upload URL");
+ }
+
+ return result.data;
+ };
+
const handleImageUploadSuccess = async (imageKey: string) => {
- await updateImage.mutateAsync({ imageKey });
+ await updateImage.executeAsync({ imageKey });
};
const handleImageRemoveSuccess = async () => {
- await removeImage.mutateAsync();
+ await removeImage.executeAsync();
};
return (
<form
onSubmit={form.handleSubmit(async (data) => {
- toast.promise(
- updateSpace
- .mutateAsync({
- name: data.name,
- })
- .then(() => {
- form.reset(data);
- }),
- {
- loading: t("updatingSpace", {
- defaultValue: "Updating space...",
- }),
- success: t("spaceUpdatedSuccess", {
+ const result = await updateSpace.executeAsync({ name: data.name });
+
+ if (!result?.serverError && !result?.validationErrors) {
+ form.reset(data);
+ toast.success(
+ t("spaceUpdatedSuccess", {
defaultValue: "Space updated successfully",
}),
- error: t("spaceUpdatedError", {
- defaultValue: "Failed to update space",
- }),
- },
- );
+ );
+ }
})}
>
<FieldGroup>
@@ -98,7 +106,7 @@ export function SpaceSettingsForm({
<SpaceIcon name={space.name} src={space.image} size="xl" />
</ImageUploadPreview>
<ImageUploadControl
- getUploadUrl={(input) => getImageUploadUrl.mutateAsync(input)}
+ getUploadUrl={handleGetUploadUrl}
onUploadSuccess={handleImageUploadSuccess}
onRemoveSuccess={handleImageRemoveSuccess}
hasCurrentImage={!!space.image}
@@ -135,7 +143,7 @@ export function SpaceSettingsForm({
<Button
type="submit"
disabled={
- disabled || updateSpace.isPending || !form.formState.isDirty
+ disabled || updateSpace.isExecuting || !form.formState.isDirty
}
>
<Trans i18nKey="save" defaults="Save" />
diff --git a/apps/web/src/features/space/actions.ts b/apps/web/src/features/space/actions.ts
index c70255d74..abb6056ff 100644
--- a/apps/web/src/features/space/actions.ts
+++ b/apps/web/src/features/space/actions.ts
@@ -1,11 +1,49 @@
"use server";
+import { subject } from "@casl/ability";
import { prisma } from "@rallly/database";
import * as z from "zod";
+import { getActiveSpaceForUser } from "@/features/space/data";
+import { defineAbilityForMember } from "@/features/space/member/ability";
+import {
+ removeSpaceImage,
+ updateSpace,
+ updateSpaceImage,
+ updateSpaceShowBranding,
+} from "@/features/space/mutations";
+import {
+ spaceImageUploadSchema,
+ updateSpaceImageSchema,
+ updateSpaceSchema,
+ updateSpaceShowBrandingSchema,
+} from "@/features/space/schema";
import { setActiveSpace } from "@/features/user/mutations";
import { AppError } from "@/lib/errors/app-error";
-import { track } from "@/lib/posthog";
+import { identifyGroup, track } from "@/lib/posthog";
import { authActionClient } from "@/lib/safe-action/server";
+import { getImageUploadUrl } from "@/lib/storage/image-upload";
+
+async function requireSpaceWithUpdateAbility(user: { id: string }) {
+ const space = await getActiveSpaceForUser(user.id);
+
+ if (!space) {
+ throw new AppError({
+ code: "NOT_FOUND",
+ message: "No active space found",
+ });
+ }
+
+ const ability = defineAbilityForMember({ user, space });
+
+ if (ability.cannot("update", subject("Space", space))) {
+ throw new AppError({
+ code: "FORBIDDEN",
+ message: "You do not have permission to update this space",
+ });
+ }
+
+ return space;
+}
export const setActiveSpaceAction = authActionClient
.metadata({ actionName: "set_active_space" })
@@ -42,3 +80,104 @@ export const setActiveSpaceAction = authActionClient
},
});
});
+
+export const updateSpaceAction = authActionClient
+ .metadata({ actionName: "update_space" })
+ .inputSchema(updateSpaceSchema)
+ .action(async ({ ctx, parsedInput }) => {
+ const space = await requireSpaceWithUpdateAbility(ctx.user);
+
+ await updateSpace({
+ spaceId: space.id,
+ name: parsedInput.name,
+ primaryColor: parsedInput.primaryColor,
+ });
+
+ track(ctx.user, {
+ event: "space_update",
+ properties: {
+ space_name: parsedInput.name,
+ },
+ groups: {
+ space: space.id,
+ },
+ });
+ });
+
+export const updateSpaceShowBrandingAction = authActionClient
+ .metadata({ actionName: "update_space_show_branding" })
+ .inputSchema(updateSpaceShowBrandingSchema)
+ .action(async ({ ctx, parsedInput }) => {
+ const space = await requireSpaceWithUpdateAbility(ctx.user);
+
+ if (parsedInput.showBranding && space.tier !== "pro") {
+ throw new AppError({
+ code: "PAYMENT_REQUIRED",
+ message: "You need a Pro subscription to enable custom branding",
+ });
+ }
+
+ await updateSpaceShowBranding({
+ spaceId: space.id,
+ showBranding: parsedInput.showBranding,
+ });
+
+ identifyGroup({
+ groupType: "space",
+ groupKey: space.id,
+ properties: {
+ custom_branding: parsedInput.showBranding,
+ },
+ });
+
+ track(ctx.user, {
+ event: "space_update_show_branding",
+ properties: {
+ showBranding: parsedInput.showBranding,
+ },
+ groups: {
+ space: space.id,
+ },
+ });
+ });
+
+export const getSpaceImageUploadUrlAction = authActionClient
+ .metadata({ actionName: "get_space_image_upload_url" })
+ .inputSchema(spaceImageUploadSchema)
+ .action(async ({ ctx, parsedInput }) => {
+ const space = await requireSpaceWithUpdateAbility(ctx.user);
+
+ return await getImageUploadUrl({
+ keyPrefix: "spaces",
+ entityId: space.id,
+ fileType: parsedInput.fileType,
+ fileSize: parsedInput.fileSize,
+ });
+ });
+
+export const updateSpaceImageAction = authActionClient
+ .metadata({ actionName: "update_space_image" })
+ .inputSchema(updateSpaceImageSchema)
+ .action(async ({ ctx, parsedInput }) => {
+ const space = await requireSpaceWithUpdateAbility(ctx.user);
+
+ if (!parsedInput.imageKey.startsWith(`spaces/${space.id}-`)) {
+ throw new AppError({
+ code: "FORBIDDEN",
+ message: "Invalid image key",
+ });
+ }
+
+ await updateSpaceImage({
+ spaceId: space.id,
+ imageKey: parsedInput.imageKey,
+ });
+ });
+
+export const removeSpaceImageAction = authActionClient
+ .metadata({ actionName: "remove_space_image" })
+ .action(async ({ ctx }) => {
+ const space = await requireSpaceWithUpdateAbility(ctx.user);
+
+ await removeSpaceImage({ spaceId: space.id });
+ });
diff --git a/apps/web/src/features/space/mutations.ts b/apps/web/src/features/space/mutations.ts
index 2b0a05b5a..b2316f246 100644
--- a/apps/web/src/features/space/mutations.ts
+++ b/apps/web/src/features/space/mutations.ts
@@ -2,8 +2,10 @@ import "server-only";
import type { SpaceTier } from "@rallly/database";
import { prisma } from "@rallly/database";
+import { after } from "next/server";
import { createSpaceDTO } from "@/features/space/data";
import { isSelfHosted } from "@/lib/constants";
+import { deleteImageFromS3 } from "@/lib/storage/image-upload";
export async function createSpace({
name = "Personal",
@@ -31,3 +33,76 @@ export async function createSpace({
return createSpaceDTO({ ...space, role: "ADMIN" });
}
+
+export async function updateSpace({
+ spaceId,
+ name,
+ primaryColor,
+}: {
+ spaceId: string;
+ name?: string;
+ primaryColor?: string | null;
+}) {
+ await prisma.space.update({
+ where: { id: spaceId },
+ data: {
+ ...(name !== undefined && { name }),
+ ...(primaryColor !== undefined && { primaryColor }),
+ },
+ });
+}
+
+export async function updateSpaceShowBranding({
+ spaceId,
+ showBranding,
+}: {
+ spaceId: string;
+ showBranding: boolean;
+}) {
+ await prisma.space.update({
+ where: { id: spaceId },
+ data: { showBranding },
+ });
+}
+
+export async function updateSpaceImage({
+ spaceId,
+ imageKey,
+}: {
+ spaceId: string;
+ imageKey: string;
+}) {
+ const space = await prisma.space.findUnique({
+ where: { id: spaceId },
+ select: { image: true },
+ });
+
+ const oldImageKey = space?.image;
+
+ await prisma.space.update({
+ where: { id: spaceId },
+ data: { image: imageKey },
+ });
+
+ if (oldImageKey) {
+ after(() => deleteImageFromS3(oldImageKey));
+ }
+}
+
+export async function removeSpaceImage({ spaceId }: { spaceId: string }) {
+ const space = await prisma.space.findUnique({
+ where: { id: spaceId },
+ select: { image: true },
+ });
+
+ const oldImageKey = space?.image;
+
+ await prisma.space.update({
+ where: { id: spaceId },
+ data: { image: null },
+ });
+
+ if (oldImageKey) {
+ after(() => deleteImageFromS3(oldImageKey));
+ }
+}
diff --git a/apps/web/src/features/space/schema.ts b/apps/web/src/features/space/schema.ts
index 14888a4fb..fabbbab62 100644
--- a/apps/web/src/features/space/schema.ts
+++ b/apps/web/src/features/space/schema.ts
@@ -5,3 +5,25 @@ export type MemberRole = z.infer<typeof memberRoleSchema>;
export const spaceTierSchema = z.enum(["hobby", "pro"]);
export type SpaceTier = z.infer<typeof spaceTierSchema>;
+
+export const updateSpaceSchema = z.object({
+ name: z.string().min(1).max(100).optional(),
+ primaryColor: z
+ .string()
+ .regex(/^#[0-9a-fA-F]{6}$/, "Invalid hex color")
+ .nullable()
+ .optional(),
+});
+
+export const updateSpaceShowBrandingSchema = z.object({
+ showBranding: z.boolean(),
+});
+
+export const spaceImageUploadSchema = z.object({
+ fileType: z.enum(["image/jpeg", "image/png"]),
+ fileSize: z.number(),
+});
+
+export const updateSpaceImageSchema = z.object({
+ imageKey: z.string().max(255),
+});
diff --git a/apps/web/src/trpc/routers/spaces.ts b/apps/web/src/trpc/routers/spaces.ts
index 67ea2a4de..15bef3bae 100644
--- a/apps/web/src/trpc/routers/spaces.ts
+++ b/apps/web/src/trpc/routers/spaces.ts
@@ -4,7 +4,6 @@ import { sendSpaceInviteEmail } from "@rallly/emails/templates/space-invite";
import { createLogger } from "@rallly/logger";
import { absoluteUrl } from "@rallly/utils/absolute-url";
import { TRPCError } from "@trpc/server";
-import { after } from "next/server";
import * as z from "zod";
import { getInstanceBranding } from "@/emails/branding";
import { defineAbilityForSpace } from "@/features/space/ability";
@@ -25,10 +24,6 @@ import {
} from "@/features/space/utils";
import { setActiveSpace } from "@/features/user/mutations";
import { identifyGroup, track } from "@/lib/posthog";
-import {
- deleteImageFromS3,
- getImageUploadUrl,
-} from "@/lib/storage/image-upload";
import {
createRateLimitMiddleware,
privateProcedure,
@@ -228,97 +223,6 @@ export const spaces = router({
});
}),
- update: spaceProcedure
- .input(
- z.object({
- name: z.string().min(1).max(100).optional(),
- primaryColor: z
- .string()
- .regex(/^#[0-9a-fA-F]{6}$/, "Invalid hex color")
- .nullable()
- .optional(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- const memberAbility = defineAbilityForMember({
- user: ctx.user,
- space: ctx.space,
- });
-
- if (memberAbility.cannot("update", subject("Space", ctx.space))) {
- throw new TRPCError({
- code: "FORBIDDEN",
- message: "You do not have permission to update this space",
- });
- }
-
- await prisma.space.update({
- where: { id: ctx.space.id },
- data: {
- ...(input.name !== undefined && { name: input.name }),
- ...(input.primaryColor !== undefined && {
- primaryColor: input.primaryColor,
- }),
- },
- });
-
- track(ctx.user, {
- event: "space_update",
- properties: {
- space_name: input.name,
- },
- groups: {
- space: ctx.space.id,
- },
- });
- }),
-
- updateShowBranding: spaceProcedure
- .input(z.object({ showBranding: z.boolean() }))
- .mutation(async ({ ctx, input }) => {
- const memberAbility = defineAbilityForMember({
- user: ctx.user,
- space: ctx.space,
- });
-
- if (memberAbility.cannot("update", subject("Space", ctx.space))) {
- throw new TRPCError({
- code: "FORBIDDEN",
- message: "You do not have permission to update this space",
- });
- }
-
- if (input.showBranding && ctx.space.tier !== "pro") {
- throw new TRPCError({
- code: "PAYMENT_REQUIRED",
- message: "You need a Pro subscription to enable custom branding",
- });
- }
-
- await prisma.space.update({
- where: { id: ctx.space.id },
- data: { showBranding: input.showBranding },
- });
-
- identifyGroup({
- groupType: "space",
- groupKey: ctx.space.id,
- properties: {
- custom_branding: input.showBranding,
- },
- });
-
- track(ctx.user, {
- event: "space_update_show_branding",
- properties: {
- showBranding: input.showBranding,
- },
- groups: {
- space: ctx.space.id,
- },
- });
- }),
-
inviteMember: spaceProcedure
.input(z.object({ email: z.email(), role: memberRoleSchema }))
.mutation(async ({ ctx, input }) => {
@@ -773,92 +677,4 @@ export const spaces = router({
},
});
}),
-
- getImageUploadUrl: spaceProcedure
- .input(
- z.object({
- fileType: z.enum(["image/jpeg", "image/png"]),
- fileSize: z.number(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- const memberAbility = defineAbilityForMember({
- user: ctx.user,
- space: ctx.space,
- });
-
- if (memberAbility.cannot("update", subject("Space", ctx.space))) {
- throw new TRPCError({
- code: "FORBIDDEN",
- message: "You do not have permission to update this space",
- });
- }
-
- return await getImageUploadUrl({
- keyPrefix: "spaces",
- entityId: ctx.space.id,
- fileType: input.fileType,
- fileSize: input.fileSize,
- });
- }),
-
- updateImage: spaceProcedure
- .input(z.object({ imageKey: z.string().max(255) }))
- .mutation(async ({ ctx, input }) => {
- const memberAbility = defineAbilityForMember({
- user: ctx.user,
- space: ctx.space,
- });
-
- if (memberAbility.cannot("update", subject("Space", ctx.space))) {
- throw new TRPCError({
- code: "FORBIDDEN",
- message: "You do not have permission to update this space",
- });
- }
-
- const expectedPrefix = `spaces/${ctx.space.id}-`;
- if (!input.imageKey.startsWith(expectedPrefix)) {
- throw new TRPCError({
- code: "BAD_REQUEST",
- message: "Invalid image key",
- });
- }
-
- const oldImageKey = ctx.space.image;
-
- await prisma.space.update({
- where: { id: ctx.space.id },
- data: { image: input.imageKey },
- });
-
- if (oldImageKey) {
- after(() => deleteImageFromS3(oldImageKey));
- }
- }),
-
- removeImage: spaceProcedure.mutation(async ({ ctx }) => {
- const memberAbility = defineAbilityForMember({
- user: ctx.user,
- space: ctx.space,
- });
-
- if (memberAbility.cannot("update", subject("Space", ctx.space))) {
- throw new TRPCError({
- code: "FORBIDDEN",
- message: "You do not have permission to update this space",
- });
- }
-
- const oldImageKey = ctx.space.image;
-
- await prisma.space.update({
- where: { id: ctx.space.id },
- data: { image: null },
- });
-
- if (oldImageKey) {
- await deleteImageFromS3(oldImageKey);
- }
- }),
});