validateMessage.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { TopicMessageSchema } from 'generated-sources';
  2. import Ajv from 'ajv/dist/2020';
  3. import { upperFirst } from 'lodash';
  4. const validateBySchema = (
  5. value: string,
  6. schema: string | undefined,
  7. type: 'key' | 'content'
  8. ) => {
  9. let errors: string[] = [];
  10. if (!value || !schema) {
  11. return errors;
  12. }
  13. let parcedSchema;
  14. let parsedValue;
  15. try {
  16. parcedSchema = JSON.parse(schema);
  17. } catch (e) {
  18. return [`Error in parsing the "${type}" field schema`];
  19. }
  20. if (parcedSchema.type === 'string') {
  21. return [];
  22. }
  23. try {
  24. parsedValue = JSON.parse(value);
  25. } catch (e) {
  26. return [`Error in parsing the "${type}" field value`];
  27. }
  28. try {
  29. const validate = new Ajv().compile(parcedSchema);
  30. validate(parsedValue);
  31. if (validate.errors) {
  32. errors = validate.errors.map(
  33. ({ schemaPath, message }) =>
  34. `${schemaPath.replace('#', upperFirst(type))} - ${message}`
  35. );
  36. }
  37. } catch (e) {
  38. return [`${upperFirst(type)} ${e.message}`];
  39. }
  40. return errors;
  41. };
  42. const validateMessage = (
  43. key: string,
  44. content: string,
  45. messageSchema: TopicMessageSchema | undefined
  46. ): string[] => [
  47. ...validateBySchema(key, messageSchema?.key?.schema, 'key'),
  48. ...validateBySchema(content, messageSchema?.value?.schema, 'content'),
  49. ];
  50. export default validateMessage;