forked from codebymitch/TitanBot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommandInputValidation.js
More file actions
52 lines (45 loc) · 1.32 KB
/
Copy pathcommandInputValidation.js
File metadata and controls
52 lines (45 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// commandInputValidation.js
import { z } from 'zod';
import { createError, ErrorTypes } from './errorHandler.js';
const OptionValueSchema = z.union([
z.string().max(2000),
z.number().finite(),
z.boolean(),
z.null()
]);
const CommandOptionSchema = z.lazy(() =>
z.object({
name: z.string().min(1).max(32),
type: z.number().int().min(1).max(20),
value: OptionValueSchema.optional(),
options: z.array(CommandOptionSchema).max(25).optional()
})
);
const CommandInputSchema = z.object({
commandName: z.string().min(1).max(32),
options: z.array(CommandOptionSchema).max(25)
});
export function validateChatInputPayloadOrThrow(interaction, context = {}) {
const payload = {
commandName: interaction?.commandName,
options: Array.isArray(interaction?.options?.data) ? interaction.options.data : []
};
const parsed = CommandInputSchema.safeParse(payload);
if (parsed.success) {
return parsed.data;
}
throw createError(
'Invalid command input payload',
ErrorTypes.VALIDATION,
'One or more command inputs are invalid. Please review your options and try again.',
{
...context,
errorCode: 'VALIDATION_FAILED',
issues: parsed.error.issues.map((issue) => ({
path: issue.path.join('.'),
message: issue.message,
code: issue.code
}))
}
);
}