validateMessage.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { TopicMessageSchema } from 'generated-sources';
  2. import Ajv from 'ajv/dist/2020';
  3. const validateMessage = async (
  4. key: string,
  5. content: string,
  6. messageSchema: TopicMessageSchema | undefined,
  7. setSchemaErrors: React.Dispatch<React.SetStateAction<string[]>>
  8. ): Promise<boolean> => {
  9. setSchemaErrors([]);
  10. const keyAjv = new Ajv();
  11. const contentAjv = new Ajv();
  12. try {
  13. if (messageSchema) {
  14. let keyIsValid = false;
  15. let contentIsValid = false;
  16. try {
  17. const keySchema = JSON.parse(messageSchema.key.schema);
  18. const validateKey = keyAjv.compile(keySchema);
  19. if (keySchema.type === 'string') {
  20. keyIsValid = true;
  21. } else {
  22. keyIsValid = validateKey(JSON.parse(key));
  23. }
  24. if (!keyIsValid) {
  25. const errorString: string[] = [];
  26. if (validateKey.errors) {
  27. validateKey.errors.forEach((e) => {
  28. errorString.push(
  29. `${e.schemaPath.replace('#', 'Key')} ${e.message}`
  30. );
  31. });
  32. setSchemaErrors((e) => [...e, ...errorString]);
  33. }
  34. }
  35. } catch (err) {
  36. setSchemaErrors((e) => [...e, `Key ${err.message}`]);
  37. }
  38. try {
  39. const contentSchema = JSON.parse(messageSchema.value.schema);
  40. const validateContent = contentAjv.compile(contentSchema);
  41. if (contentSchema.type === 'string') {
  42. contentIsValid = true;
  43. } else {
  44. contentIsValid = validateContent(JSON.parse(content));
  45. }
  46. if (!contentIsValid) {
  47. const errorString: string[] = [];
  48. if (validateContent.errors) {
  49. validateContent.errors.forEach((e) => {
  50. errorString.push(
  51. `${e.schemaPath.replace('#', 'Content')} ${e.message}`
  52. );
  53. });
  54. setSchemaErrors((e) => [...e, ...errorString]);
  55. }
  56. }
  57. } catch (err) {
  58. setSchemaErrors((e) => [...e, `Content ${err.message}`]);
  59. }
  60. return keyIsValid && contentIsValid;
  61. }
  62. } catch (err) {
  63. setSchemaErrors((e) => [...e, err.message]);
  64. }
  65. return false;
  66. };
  67. export default validateMessage;