EditHookPanel.constants.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { getKeyValueFieldArrayValidationIssues } from 'ui-patterns/form/KeyValueFieldArray/validation'
  2. import { z } from 'zod'
  3. import { httpEndpointUrlSchema } from '@/lib/validation/http-url'
  4. const httpRequestSchema = z.object({
  5. function_type: z.literal('http_request'),
  6. http_url: httpEndpointUrlSchema({
  7. requiredMessage: 'Please provide a URL',
  8. invalidMessage: 'Please provide a valid URL',
  9. prefixMessage: 'Please prefix your URL with http:// or https://',
  10. }),
  11. })
  12. const brivenFunctionSchema = z.object({
  13. function_type: z.literal('briven_function'),
  14. http_url: z
  15. .string()
  16. .min(1, 'Please select an edge function')
  17. .refine((val) => !val.includes('undefined'), 'No edge functions available for selection'),
  18. })
  19. const httpHeadersSchema = z.array(
  20. z.object({ id: z.string(), name: z.string().trim(), value: z.string().trim() })
  21. )
  22. const httpParametersSchema = z.array(
  23. z.object({ id: z.string(), name: z.string().trim(), value: z.string().trim() })
  24. )
  25. const addKeyValueIssues = (
  26. rows: z.infer<typeof httpHeadersSchema> | z.infer<typeof httpParametersSchema>,
  27. ctx: z.RefinementCtx,
  28. pathPrefix: 'httpHeaders' | 'httpParameters'
  29. ) => {
  30. const isHeaderField = pathPrefix === 'httpHeaders'
  31. getKeyValueFieldArrayValidationIssues({
  32. rows,
  33. keyFieldName: 'name',
  34. valueFieldName: 'value',
  35. keyRequiredMessage: isHeaderField ? 'Header name is required' : 'Parameter name is required',
  36. valueRequiredMessage: isHeaderField
  37. ? 'Header value is required'
  38. : 'Parameter value is required',
  39. }).forEach((issue) => {
  40. ctx.addIssue({
  41. code: z.ZodIssueCode.custom,
  42. message: issue.message,
  43. path: [pathPrefix, ...issue.path],
  44. })
  45. })
  46. }
  47. export const FormSchema = z
  48. .object({
  49. name: z.string().min(1, 'Please provide a name for your webhook'),
  50. table_id: z.string().min(1, 'Please select a table'),
  51. http_method: z.enum(['GET', 'POST']),
  52. timeout_ms: z.coerce
  53. .number()
  54. .int()
  55. .gte(1000, 'Timeout should be at least 1000ms')
  56. .lte(10000, 'Timeout should not exceed 10,000ms'),
  57. events: z.array(z.string()).min(1, 'Please select at least one event'),
  58. httpHeaders: httpHeadersSchema,
  59. httpParameters: httpParametersSchema,
  60. })
  61. .and(z.discriminatedUnion('function_type', [httpRequestSchema, brivenFunctionSchema]))
  62. .superRefine((data, ctx) => {
  63. addKeyValueIssues(data.httpHeaders, ctx, 'httpHeaders')
  64. addKeyValueIssues(data.httpParameters, ctx, 'httpParameters')
  65. })
  66. export type WebhookFormValues = z.infer<typeof FormSchema>