Skip to content

Commit 6904781

Browse files
refactor: extract Zod validation logic into generic helper (#51)
1 parent 76fcafa commit 6904781

1 file changed

Lines changed: 22 additions & 32 deletions

File tree

‎workspace-server/src/utils/validation.ts‎

Lines changed: 22 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -105,49 +105,39 @@ export const pageSizeSchema = z.number()
105105

106106

107107
/**
108-
* Helper function to validate email
108+
* Helper function to create a validator from a Zod schema
109109
*/
110-
export function validateEmail(email: string): { success: boolean; error?: string } {
111-
try {
112-
emailSchema.parse(email);
113-
return { success: true };
114-
} catch (error) {
115-
if (error instanceof z.ZodError) {
116-
return { success: false, error: error.issues[0].message };
110+
function createValidator<T>(
111+
schema: z.ZodSchema<T>,
112+
fallbackErrorMessage: string
113+
) {
114+
return (value: unknown): { success: boolean; error?: string } => {
115+
try {
116+
schema.parse(value);
117+
return { success: true };
118+
} catch (error) {
119+
if (error instanceof z.ZodError) {
120+
return { success: false, error: error.issues[0].message };
121+
}
122+
return { success: false, error: fallbackErrorMessage };
117123
}
118-
return { success: false, error: 'Invalid email format' };
119-
}
124+
};
120125
}
121126

127+
/**
128+
* Helper function to validate email
129+
*/
130+
export const validateEmail = createValidator(emailSchema, 'Invalid email format');
131+
122132
/**
123133
* Helper function to validate ISO 8601 datetime
124134
*/
125-
export function validateDateTime(datetime: string): { success: boolean; error?: string } {
126-
try {
127-
iso8601DateTimeSchema.parse(datetime);
128-
return { success: true };
129-
} catch (error) {
130-
if (error instanceof z.ZodError) {
131-
return { success: false, error: error.issues[0].message };
132-
}
133-
return { success: false, error: 'Invalid datetime format' };
134-
}
135-
}
135+
export const validateDateTime = createValidator(iso8601DateTimeSchema, 'Invalid datetime format');
136136

137137
/**
138138
* Helper function to validate Google document ID
139139
*/
140-
export function validateDocumentId(id: string): { success: boolean; error?: string } {
141-
try {
142-
googleDocumentIdSchema.parse(id);
143-
return { success: true };
144-
} catch (error) {
145-
if (error instanceof z.ZodError) {
146-
return { success: false, error: error.issues[0].message };
147-
}
148-
return { success: false, error: 'Invalid document ID' };
149-
}
150-
}
140+
export const validateDocumentId = createValidator(googleDocumentIdSchema, 'Invalid document ID');
151141

152142
/**
153143
* Helper function to extract document ID from URL or return the ID if already valid

0 commit comments

Comments
 (0)