From f984ee0fcc649335aa77cafe0fd1c428e30b0bda Mon Sep 17 00:00:00 2001 From: Tom Moor Date: Sat, 7 Sep 2024 18:42:39 -0400 Subject: [PATCH] fix: Cannot unset collection description, closes #7553 --- server/routes/api/collections/schema.ts | 4 ++-- server/routes/api/comments/schema.ts | 4 ++-- server/routes/api/schema.ts | 26 ++++++++++++++++--------- 3 files changed, 21 insertions(+), 13 deletions(-) diff --git a/server/routes/api/collections/schema.ts b/server/routes/api/collections/schema.ts index d1b5f15d01..24a9574200 100644 --- a/server/routes/api/collections/schema.ts +++ b/server/routes/api/collections/schema.ts @@ -19,7 +19,7 @@ export const CollectionsCreateSchema = BaseSchema.extend({ .regex(ValidateColor.regex, { message: ValidateColor.message }) .nullish(), description: z.string().nullish(), - data: ProsemirrorSchema.nullish(), + data: ProsemirrorSchema({ allowEmpty: true }).nullish(), permission: z .nativeEnum(CollectionPermission) .nullish() @@ -152,7 +152,7 @@ export const CollectionsUpdateSchema = BaseSchema.extend({ body: BaseIdSchema.extend({ name: z.string().optional(), description: z.string().nullish(), - data: ProsemirrorSchema.nullish(), + data: ProsemirrorSchema({ allowEmpty: true }).nullish(), icon: zodIconType().nullish(), permission: z.nativeEnum(CollectionPermission).nullish(), color: z diff --git a/server/routes/api/comments/schema.ts b/server/routes/api/comments/schema.ts index a9b16b36d4..6518054fd1 100644 --- a/server/routes/api/comments/schema.ts +++ b/server/routes/api/comments/schema.ts @@ -33,7 +33,7 @@ export const CommentsCreateSchema = BaseSchema.extend({ parentCommentId: z.string().uuid().optional(), /** Create comment with this data */ - data: ProsemirrorSchema, + data: ProsemirrorSchema(), }), }); @@ -42,7 +42,7 @@ export type CommentsCreateReq = z.infer; export const CommentsUpdateSchema = BaseSchema.extend({ body: BaseIdSchema.extend({ /** Update comment with this data */ - data: ProsemirrorSchema, + data: ProsemirrorSchema(), }), }); diff --git a/server/routes/api/schema.ts b/server/routes/api/schema.ts index d44772f012..18934c4445 100644 --- a/server/routes/api/schema.ts +++ b/server/routes/api/schema.ts @@ -11,12 +11,20 @@ export const BaseSchema = z.object({ file: z.custom().optional(), }); -export const ProsemirrorSchema = z.custom((val) => { - try { - const node = Node.fromJSON(schema, val); - node.check(); - return !ProsemirrorHelper.isEmpty(node, schema); - } catch (_e) { - return false; - } -}, "not valid data"); +/** + * Returns a Zod schema for validating a Prosemirror document. + * + * @param allowEmpty - Whether to allow an empty document. + */ +export const ProsemirrorSchema = (options?: { allowEmpty: boolean }) => + z.custom((val) => { + try { + const node = Node.fromJSON(schema, val); + node.check(); + return options?.allowEmpty + ? true + : !ProsemirrorHelper.isEmpty(node, schema); + } catch (_e) { + return false; + } + }, "Invalid data");