UNPKG

@tmlmobilidade/types

Version:
56 lines (55 loc) 1.7 kB
/* * */ import { DocumentSchema } from './document.js'; import { z } from 'zod'; /* * */ const COMMENT_TYPE_OPTIONS = ['field_changed', 'note', 'crud']; export const CommentTypeSchema = z.enum(COMMENT_TYPE_OPTIONS); const CRUD_COMMENT_ACTION_OPTIONS = ['create', 'update', 'delete', 'archive', 'restore']; export const CrudCommentSchemaActionSchema = z.enum(CRUD_COMMENT_ACTION_OPTIONS); /* * */ export const NoteCommentSchema = DocumentSchema .omit({ is_locked: true }) .extend({ message: z.string(), type: z.literal(CommentTypeSchema.enum.note), }) .partial({ _id: true }); export const FieldChangedCommentSchema = DocumentSchema .omit({ is_locked: true }) .extend({ curr_value: z.any(), field: z.string(), metadata: z.record(z.unknown()).nullish(), prev_value: z.any(), type: z.literal(CommentTypeSchema.enum.field_changed), }) .partial({ _id: true }); export const CrudCommentSchema = DocumentSchema .omit({ is_locked: true }) .extend({ action: CrudCommentSchemaActionSchema, type: z.literal(CommentTypeSchema.enum.crud), }) .partial({ _id: true }); /* * */ function validateFieldChanged(data, ctx) { if (data.curr_value === data.prev_value) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'curr_value and prev_value must differ', path: ['curr_value'], }); } } /* * */ export const CommentSchema = z .discriminatedUnion('type', [ NoteCommentSchema, FieldChangedCommentSchema, CrudCommentSchema, ]) .superRefine((data, ctx) => { if (data.type === CommentTypeSchema.enum.field_changed) { validateFieldChanged(data, ctx); } });