Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

add POST handler for editing a page

Roman Pominov18f2b99d545e
diff --git a/apps/designer/app/routes/rest/pages.$projectId.ts b/apps/designer/app/routes/rest/pages.$projectId.ts
index b4ecd6906d..174c13d427 100644
--- a/apps/designer/app/routes/rest/pages.$projectId.ts
+++ b/apps/designer/app/routes/rest/pages.$projectId.ts
@@ -3,7 +3,10 @@ import { db } from "@webstudio-is/project/index.server";
import { type Pages, utils } from "@webstudio-is/project";
import { zfd } from "zod-form-data";
import { z } from "zod";
-import { CreatePageData } from "~/designer/features/sidebar-left/panels/pages/settings";
+import {
+ CreatePageData,
+ EditPageData,
+} from "~/designer/features/sidebar-left/panels/pages/settings";
import { sentryException } from "~/shared/sentry";
const nonEmptyString = z
@@ -14,7 +17,7 @@ const nonEmptyString = z
.transform((value) => value.trim())
.refine((value) => value !== "", "Can't be empty");
-const CreatePageInput = zfd.formData({
+const commonPageInput = {
name: nonEmptyString,
path: nonEmptyString
.refine((path) => path !== "/", "Can't be just a /")
@@ -28,7 +31,9 @@ const CreatePageInput = zfd.formData({
(path) => /^[-_a-z0-9\\/]*$/.test(path),
"Only a-z, 0-9, -, _ and / are allowed"
),
-});
+} as const;
+
+const CreatePageInput = zfd.formData(commonPageInput);
const handlePut = async (
projectId: string,
@@ -44,14 +49,7 @@ const handlePut = async (
const existingPage = utils.pages.findByPath(devBuild.pages, data.path);
if (existingPage !== undefined) {
- return {
- errors: {
- formErrors: [],
- fieldErrors: {
- path: [`Already used for "${existingPage.name}"`],
- },
- },
- };
+ return fieldError("path", `Already used for "${existingPage.name}"`);
}
const updatedBuild = await db.build.addPage(devBuild.id, data);
@@ -65,6 +63,36 @@ const handlePut = async (
return { ok: true, page: newPage };
};
+const EditPageInput = zfd.formData({
+ id: z.string(),
+ name: z.optional(commonPageInput.name),
+ path: z.optional(commonPageInput.path),
+});
+
+const handlePost = async (
+ projectId: string,
+ request: Request
+): Promise<EditPageData> => {
+ const result = EditPageInput.safeParse(await request.formData());
+ if (result.success === false) {
+ return { errors: result.error.formErrors };
+ }
+ const { id, ...data } = result.data;
+
+ const devBuild = await db.build.loadByProjectId(projectId, "dev");
+
+ if (data.path !== undefined) {
+ const existingPage = utils.pages.findByPath(devBuild.pages, data.path);
+ if (existingPage !== undefined && existingPage.id !== id) {
+ return fieldError("path", `Already used for "${existingPage.name}"`);
+ }
+ }
+
+ await db.build.editPage(devBuild.id, id, data);
+
+ return { ok: true };
+};
+
export const action: ActionFunction = async ({ request, params }) => {
try {
if (params.projectId === undefined) {
@@ -72,8 +100,11 @@ export const action: ActionFunction = async ({ request, params }) => {
}
if (request.method === "PUT") {
- const result = await handlePut(params.projectId, request);
- return result;
+ return await handlePut(params.projectId, request);
+ }
+
+ if (request.method === "POST") {
+ return await handlePost(params.projectId, request);
}
throw new Error(`Method ${request.method} is not supported`);
@@ -113,3 +144,12 @@ export const loader: LoaderFunction = async ({
};
}
};
+
+const fieldError = (fieldName: string, error: string) => {
+ return {
+ errors: {
+ formErrors: [],
+ fieldErrors: { [fieldName]: [error] },
+ },
+ };
+};
diff --git a/packages/project/src/db/build.ts b/packages/project/src/db/build.ts
index 11da1d4134..eb48cd838d 100644
--- a/packages/project/src/db/build.ts
+++ b/packages/project/src/db/build.ts
@@ -3,6 +3,7 @@ import { type Breakpoint } from "@webstudio-is/react-sdk";
import { v4 as uuid } from "uuid";
import * as db from ".";
import { Build, Page, Pages } from "./types";
+import * as pagesUtils from "../shared/pages";
export const parseBuild = (build: DbBuild): Build => {
const pages = Pages.parse(JSON.parse(build.pages));
@@ -61,38 +62,77 @@ export async function loadByProjectId(
return parseBuild(build);
}
-export const addPage = async (
+const updatePages = async (
buildId: Build["id"],
- data: { name: string; path: string }
+ updater: (currentPages: Pages) => Promise<Pages>
) => {
const build = await loadById(buildId);
-
- const breakpoints = await db.breakpoints.load(buildId);
- const tree = await db.tree.create(
- db.tree.createRootInstance(breakpoints.values)
- );
-
- const nextPages = Pages.parse({
- homePage: build.pages.homePage,
- pages: [
- ...build.pages.pages,
- {
- id: uuid(),
- name: data.name,
- path: data.path,
- title: data.name,
- meta: {},
- treeId: tree.id,
- },
- ],
+ const updatedPages = Pages.parse(await updater(build.pages));
+ const updatedBuild = await prisma.build.update({
+ where: { id: buildId },
+ data: { pages: JSON.stringify(updatedPages) },
});
+ return parseBuild(updatedBuild);
+};
- const newBuild = await prisma.build.update({
- where: { id: buildId },
- data: { pages: JSON.stringify(nextPages) },
+export const addPage = async (
+ buildId: Build["id"],
+ data: Pick<Page, "name" | "path"> &
+ Partial<Omit<Page, "id" | "treeId" | "name" | "path">>
+) => {
+ return updatePages(buildId, async (currentPages) => {
+ const breakpoints = await db.breakpoints.load(buildId);
+ const tree = await db.tree.create(
+ db.tree.createRootInstance(breakpoints.values)
+ );
+
+ return {
+ homePage: currentPages.homePage,
+ pages: [
+ ...currentPages.pages,
+ {
+ id: uuid(),
+ treeId: tree.id,
+ name: data.name,
+ path: data.path,
+ title: data.title ?? data.name,
+ meta: data.meta ?? {},
+ },
+ ],
+ };
});
+};
- return parseBuild(newBuild);
+export const editPage = async (
+ buildId: Build["id"],
+ pageId: Page["id"],
+ data: Partial<Omit<Page, "id" | "treeId">>
+) => {
+ return updatePages(buildId, async (currentPages) => {
+ const currentPage = pagesUtils.findById(currentPages, pageId);
+ if (currentPage === undefined) {
+ throw new Error(`Page with id "${pageId}" not found`);
+ }
+
+ const updatedPage: Page = {
+ id: currentPage.id,
+ treeId: currentPage.treeId,
+ name: data.name ?? currentPage.name,
+ path: data.path ?? currentPage.path,
+ title: data.title ?? currentPage.title,
+ meta: data.meta ?? currentPage.meta,
+ };
+
+ return {
+ homePage:
+ updatedPage.id === currentPages.homePage.id
+ ? updatedPage
+ : currentPages.homePage,
+ pages: currentPages.pages.map((page) =>
+ page.id === updatedPage.id ? updatedPage : page
+ ),
+ };
+ });
};
const createPages = async (breakpoints: Array<Breakpoint>) => {