yupExtended.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import * as yup from 'yup';
  2. import { AnyObject, Maybe } from 'yup/lib/types';
  3. import { TOPIC_NAME_VALIDATION_PATTERN } from './constants';
  4. declare module 'yup' {
  5. interface StringSchema<
  6. TType extends Maybe<string> = string | undefined,
  7. TContext extends AnyObject = AnyObject,
  8. TOut extends TType = TType
  9. > extends yup.BaseSchema<TType, TContext, TOut> {
  10. isJsonObject(): StringSchema<TType, TContext>;
  11. }
  12. }
  13. export const isValidJsonObject = (value?: string) => {
  14. try {
  15. if (!value) return false;
  16. const trimmedValue = value.trim();
  17. if (
  18. trimmedValue.indexOf('{') === 0 &&
  19. trimmedValue.lastIndexOf('}') === trimmedValue.length - 1
  20. ) {
  21. JSON.parse(trimmedValue);
  22. return true;
  23. }
  24. } catch {
  25. // do nothing
  26. }
  27. return false;
  28. };
  29. const isJsonObject = () => {
  30. return yup.string().test(
  31. 'isJsonObject',
  32. // eslint-disable-next-line no-template-curly-in-string
  33. '${path} is not JSON object',
  34. isValidJsonObject
  35. );
  36. };
  37. yup.addMethod(yup.string, 'isJsonObject', isJsonObject);
  38. export default yup;
  39. export const topicFormValidationSchema = yup.object().shape({
  40. name: yup
  41. .string()
  42. .required()
  43. .matches(
  44. TOPIC_NAME_VALIDATION_PATTERN,
  45. 'Only alphanumeric, _, -, and . allowed'
  46. ),
  47. partitions: yup
  48. .number()
  49. .min(1)
  50. .required()
  51. .typeError('Number of partitions is required and must be a number'),
  52. replicationFactor: yup
  53. .number()
  54. .min(1)
  55. .required()
  56. .typeError('Replication factor is required and must be a number'),
  57. minInsyncReplicas: yup
  58. .number()
  59. .min(1)
  60. .required()
  61. .typeError('Min in sync replicas is required and must be a number'),
  62. cleanupPolicy: yup.string().required(),
  63. retentionMs: yup
  64. .number()
  65. .min(-1, 'Must be greater than or equal to -1')
  66. .typeError('Time to retain data is required and must be a number'),
  67. retentionBytes: yup.number(),
  68. maxMessageBytes: yup
  69. .number()
  70. .min(1)
  71. .required()
  72. .typeError('Maximum message size is required and must be a number'),
  73. customParams: yup.array().of(
  74. yup.object().shape({
  75. name: yup.string().required('Custom parameter is required'),
  76. value: yup.string().required('Value is required'),
  77. })
  78. ),
  79. });