Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: refactor zod validation #739

Merged
merged 2 commits into from
Feb 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 2 additions & 6 deletions api/src/chat/schemas/types/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -309,14 +309,9 @@ export type StdOutgoingEnvelope = z.infer<typeof stdOutgoingEnvelopeSchema>;

// is-valid-message-text validation
export const validMessageTextSchema = z.object({
message: z.string(),
text: z.string(),
});

// is-message validation
const MESSAGE_REGEX = /^function \(context\) \{[^]+\}/;

export const messageRegexSchema = z.string().regex(MESSAGE_REGEX);

export const textSchema = z.array(z.string().max(1000));

const quickReplySchema = z
Expand Down Expand Up @@ -391,6 +386,7 @@ const attachmentBlockMessageSchema = z.object({

// BlockMessage Schema
export const blockMessageObjectSchema = z.union([
textSchema,
pluginBlockMessageSchema,
textBlockMessageSchema,
buttonMessageSchema,
Expand Down
27 changes: 1 addition & 26 deletions api/src/chat/validation-rules/is-message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,36 +16,11 @@ import {
import {
BlockMessage,
blockMessageObjectSchema,
messageRegexSchema,
textSchema,
} from '../schemas/types/message';

/* eslint-disable no-console */
export function isValidMessage(msg: any) {
if (typeof msg === 'string' && msg !== '') {
const result = messageRegexSchema.safeParse(msg);
if (!result.success) {
console.error('Block Model: Invalid custom code.', result.error);
return false;
}
return true;
} else if (Array.isArray(msg)) {
const result = textSchema.safeParse(msg);
if (!result.success) {
console.error('Block Model: Invalid text message array.', result.error);
}
return result.success;
} else if (typeof msg === 'object' && msg !== null) {
const result = blockMessageObjectSchema.safeParse(msg);
if (!result.success) {
console.error('Block Model: Object validation failed!', result.error);
}
return result.success;
}
console.log('Validation reached default false');
return false;
return blockMessageObjectSchema.safeParse(msg).success;
}
/* eslint-enable no-console */

@ValidatorConstraint({ async: false })
export class MessageValidator implements ValidatorConstraintInterface {
Expand Down